而变量不等于x或y bash

Zvi*_*Zvi 7 syntax bash

我正在尝试获取用户输入.输入应为"1"或"2".出于某种原因,即使我输入1或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
Run Code Online (Sandbox Code Playgroud)

我将感激你的帮助谢谢!

che*_*ner 21

!=不分发||,连接两个完整的表达式.一旦修复,您将需要使用&&而不是||.

while [[ "$UserChoice" != "1" && "$UserChoice" != "2" ]]
Run Code Online (Sandbox Code Playgroud)

实际上,bash是否支持模式匹配,可以与您的想法类似地使用.

while [[ $UserChoice != [12] ]]
Run Code Online (Sandbox Code Playgroud)

使用extglob选项集(默认情况下[[ ... ]]在bash 4.2中开始,我相信),你可以使用非常接近你原来的东西:

while [[ $UserChoice != @(1|2) ]]
Run Code Online (Sandbox Code Playgroud)