13

I'm trying to get user input. The input should be "1" or "2". for some reason I keep getting prompt even when I type 1 or 2.

read -p "Your choice:  " UserChoice
            while [[ "$UserChoice" != "1" || "2" ]]
            do
                echo -e "\nInvalid choice please choose 1 or 2\n"
                read -p "Your choice:  " UserChoice
            done

I'll appreciate your help Thanks!

Zvi
  • 312
  • 1
  • 3
  • 10

1 Answers1

31

!= does not distribute over ||, which joins two complete expressions. Once that is fixed, you'll need to use && instead of || as well.

while [[ "$UserChoice" != "1" && "$UserChoice" != "2" ]]

Actually, bash does support pattern matching which can be used similarly to what you had in mind.

while [[ $UserChoice != [12] ]]

With the extglob option set (which is on by default inside [[ ... ]] starting in bash 4.2, I believe), you can use something very close to what you originally had:

while [[ $UserChoice != @(1|2) ]]
chepner
  • 497,756
  • 71
  • 530
  • 681
  • No; the unquoted righthand side of the `!=` operator, inside `[[ ... ]]`, is treated as a pattern. Hm. Almost. (I mixed up regular patterns and extended patterns.) – chepner Sep 16 '14 at 20:22
  • Thanks Chepner, I used the your second offer, that worked perfectly. But I don't understand how it works cause the numbers are not separated. Why the BASH interpreter consider it as 1 and 2 and not as 12? – Zvi Sep 16 '14 at 20:46