0

I am trying to check if the the variable $userSelection is not having value 1, 2 or 3, then I display error message. Tried the following and other combinations, but no luck.

if [ $userSelection -ne 1 || $userSelection -ne 2 ] || [ $userSelection -ne 2 || $userSelection -ne 3 ]
then 
    echo "Option selected not valid...please try again."
fi

Am getting error [: missing]'`.

6
  • 1
    You've got a rogue bracket in there [ $userSelection -ne 2 Easy to miss with all those bars. Commented Mar 1, 2018 at 18:51
  • 3
    [ is a command. It has the odd behavior of requiring that its last argument be ]. You are trying to run the command [ $userSelection -ne 1 and then (if it is successful) the command $userSelection -ne 2. You must stop thinking of [ as being a symbol in the grammar of the shell. It is just a command. This is often more clear if you spell it test (which is exactly the same as [, except that it does not require that its final argument be ]) Commented Mar 1, 2018 at 19:08
  • @WilliamPursell I really like your explanation. Great one! Commented Mar 1, 2018 at 19:11
  • @JNevill Thanks for highlighting that...classic mistake of overlooking Commented Mar 1, 2018 at 19:23
  • @JNevill Actually, that [ is necessary to start a new command, because [ doesn't support ||. He's actually missing quite a few brackets. Commented Mar 1, 2018 at 19:36

2 Answers 2

4

For your actual needs the right code should be the following:

if [ "$userSelection" -ne 1 ] && [ "$userSelection" -ne 2 ] && [ "$userSelection" -ne 3 ]
then 
    echo "Option selected not valid...please try again."
fi

From what you are saying the only right choices should be 1,2 or 3.

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

1 Comment

Yes! Thanks a bunch
1

Missing brackets aside, the simplest way to make such a check is with a case statement instead:

case $userSelection in
   1|2|3) ;;
   *) echo "Option selected not valid...please try again." ;;
esac

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.