Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while variable is not equal to x or y bash

Tags:

syntax

bash

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!

like image 517
Zvi Avatar asked Sep 16 '14 20:09

Zvi


1 Answers

!= 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) ]]
like image 186
chepner Avatar answered Oct 15 '22 02:10

chepner