Search code examples
bashshellwhile-looposx-maverickssh

Mutiple conditions in OS X bash script WHILE loop


Basically what i want to do is read in a variable from std input and check if the variable is 1 or 2. if it is not i want to inform the user and ask again, i thought a while loop was made sense (i am using OS X Mavericks in a bash shell)

For a single condition this works:

read result

while [[ "$result" != "1" ]];
do
echo $result
echo "You must enter 1 or 2. Please try again: "
read result
done
echo "success"

but when i try to do an or condition:

while [[ "$result" != "1" ]] || [[ "$result" != "2" ]];

if i enter 1 or 2 into the terminal this doesn't match the input 1 or 2. I have also tried

while [[ "$result" != "1" ] || [ "$result" != "2" ]];

which produces a syntax error.

while [[ "$result" != "1" || "$result" != "2" ]];

and this doesn't match 1 or 2 either. Does anyone know the correct syntax??


Solution

  • Actually you need to use && (AND) instead of ||, so use:

    while [[ "$result" != "1" && "$result" != "2" ]];
    

    It is because you are checking if $result is not 1 and not 2