36

Okay, essentially this is what the script looks like:

echo -n "Guess my number: "
read guess

while [ $guess != 5 ]; do
echo Your answer is $guess. This is incorrect. Please try again.
echo -n "What is your guess? "
read guess
done

echo "That's correct! The answer was $guess!"

What I want to change is this line:

while [ $guess != 5 ]; do

To something like this:

while [ $guess != 5 and $guess != 10 ]; do

In Java I know "and" is " && " but that doesn't seem to work here. Am I going about this the right way using a while loop?

1
  • The question title was originally "or" instead of "and". Of course, per de Morgan's law, it's logically all the same whether you phrase the requirement as "I want 5 or 10" or with a double negation "I don't want an answer which isn't 5 and isn't 10". Commented Jul 8, 2019 at 3:51

3 Answers 3

63

There are 2 correct and portable ways to achieve what you want.
Good old shell syntax:

while [ "$guess" != 5 ] && [ "$guess" != 10 ]; do

And bash syntax (as you specify):

while [[ "$guess" != 5 && "$guess" != 10 ]]; do
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for taking the time to let me know, I noticed now I wasn't bracketing off the two statements and that was why it wasn't working.
34

The [] operator in bash is syntactic sugar for a call to test, which is documented in man test. "or" is expressed by an infix -o, but you need an "and":

while [ $guess != 5 -a $guess != 10 ]; do

2 Comments

yep, my mistake "and" was the one I should be using. That'll explain why "-o" didn't work when I tried it earlier; I just thought it was applicable only to if statements when it gave me an error. Thank you very much for your prompt response!
Note: this is not POSIX and so not portable.
2

The portable and robust way is to use a case statement instead. If you are not used to it, it might take a few looks just to wrap your head around the syntax.

while true; do
    case $guess in 5 | 10) break ;; esac
    echo Your answer is $guess. This is incorrect. Please try again.
    echo -n "What is your guess? "
    read guess  # not $guess
done

I used while true but you could in fact use the case statement there directly. It gets hairy to read and maintain, though.

while case $guess in 5 | 10) false;; *) true;; esac; do ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.