10

I have a variable called choice. Now, I try to use if to compare the entered value:

read $choice if [ "$choice" == 2 ];then #do something elif [ "$choice" == 1 ];then #do something else else echo "Invalid choice!!" fi 

The output goes directly to invalid choice if I enter either 1 or 2. I tried to put quotes around 1 and 2 inside the if statement. Still didn't work. Using -eq gives me an error "Unary operator expected".What am I doing wrong here?

3 Answers 3

24

Your read line is incorrect. Change it to:

read choice 

i.e. use the name of the variable you want to set, not its value.

-eq is the correct test to compare integers. See man test for the descriptions (or man bash).

An alternative would be using arithmetic evaluation instead (but you still need the correct read statement):

read choice if (( $choice == 2 )) ; then echo 2 elif (( $choice == 1 )) ; then echo 1 else echo "Invalid choice!!" fi 
Sign up to request clarification or add additional context in comments.

4 Comments

Now I feel utterly dumb. :( Thanks for your help (and the quick reply), Mat!!
you mean "its" value; if "it is" doesn't sound right then "it's" isn't
Hmmm, coping and pasting this with a BusyBox sheel seems to fail. When, for example, I enter 2 for choice, I get the errors... -ash: 2: not found -ash: 2: not found Any ideas what is going wrong?
ash isn't bash. Try devnull's case variant, it's more portable.
6

For your example, case seems to be what you probably want:

read choice case "$choice" in "1") echo choice 1; ;; "2") echo choice 2; ;; *) echo "invalid choice" ;; esac 

Comments

4

An unpractical answer, just to point out that since read takes a variable name, the name can be specified by another variable.

choice=choice # A variable whose value is the string "choice" read $choice # $choice expands to "choice", so read sets the value of that variable if [[ $choice -eq 1 ]]; then # or (( choice == 1 )) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.