ksa_coder
ksa_coder

Reputation: 1413

Bash - checking variable value

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]'`.

Upvotes: 0

Views: 114

Answers (2)

chepner
chepner

Reputation: 532448

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

Upvotes: 1

shadowsheep
shadowsheep

Reputation: 15022

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.

Upvotes: 4

Related Questions