Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??

like image 598
Tyler Durden Avatar asked Apr 09 '26 20:04

Tyler Durden


1 Answers

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

like image 79
anubhava Avatar answered Apr 11 '26 12:04

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!