while 变量不等于 x 或 y bash

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25877637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:40:41  来源:igfitidea点击:

while variable is not equal to x or y bash

bashsyntax

提问by Zvi

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.

我正在尝试获取用户输入。输入应为“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

I'll appreciate your help Thanks!

我会很感激你的帮助 谢谢!

回答by chepner

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

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

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

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

实际上,bash确实支持模式匹配,可以类似于您想到的那样使用。

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

With the extgloboption 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:

通过extglob选项设置(这是在默认情况下里面[[ ... ]]在bash 4.2开始,我相信),你可以使用的东西非常接近,你本来有哪些:

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