0

When running the code below, I’d like to read a user-input answer until it is one of the 6 possible answers ([abcABC]), else continue with the next loop.

However, it does not exit the while loop when I enter one of the accepted answers.

I tried [] and [[]] for the conditions, I tried to place all of the conditions into one pair of square brackets, I tried to use | and ||, none of them worked as expected.

while [ "$ans" != "a" ] || [ "$ans" != "A" ] || [ "$ans" != "b" ] || \
      [ "$ans" != "B" ] || [ "$ans" != "c" ] || [ "$ans" != "C" ]; do
    read ans

    case $ans in
      [aA]) echo "aA"         ;;
      [bB]) echo "bB"         ;;
      [cC]) echo "cC"         ;;
      *)    echo "Try again." ;;
    esac
done

It should read in loop until one of the accepted answer is given; then it should continue with the following code (if any).

1 Answer 1

2

Your loop condition is always true, and Bash correctly loops forever.

Consider a simplified version:

[ "$ans" != "a" ] || [ "$ans" != "b" ]
  • If ans is a then it becomes false || true which is true.
  • If ans is b then it becomes true || false which is true.
  • If ans is x then it becomes true || true which is true.

You wanted && instead of ||. Alternatively, do it in a single comparison: [[ "$ans" != [aAbBcC] ]]

Sign up to request clarification or add additional context in comments.

1 Comment

This is the perfect answer! Yes, I see the reason. I have no idea why missed this. Anyway, thank you for the simplifacation --- I did not know I can use regex syntax instead of a string in comparison.

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.