And the variable is not equal to x or y bash

I am trying to get user input. The input must be "1" or "2". for some reason I get a hint 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 would be grateful for your help Thank you!

+4
source share
1 answer

!=not distributed by ||, which combines two complete expressions. Once this is fixed, you need to use &&instead ||.

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

Actually, it bashsupports pattern matching, which can be used similarly to what you had in mind.

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

extglob ( [[ ... ]], bash 4.2, ), - , :

while [[ $UserChoice != @(1|2) ]]
+14

All Articles