Linux 在 Bash while 循环中使用“and”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8239197/
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-08-06 02:31:43  来源:igfitidea点击:

Using "and" in Bash while loop

linuxbash

提问by Smitty

Okay, essentially this is what the script looks like:

好的,基本上这就是脚本的样子:

echo -n "Guess my number: "
read guess

while [ $guess != 5 ]; do
echo Your answer is $guess. This is incorrect. Please try again.
echo -n "What is your guess? "
read guess
done

echo "That's correct! The answer was $guess!"

What I want to change is this line:

我想改变的是这一行:

while [ $guess != 5 ]; do

To something like this:

对于这样的事情:

while [ $guess != 5 and $guess != 10 ]; do

In Java I know "and" is " && " but that doesn't seem to work here. Am I going about this the right way using a while loop?

在 Java 中,我知道“and”是“&&”,但这在这里似乎不起作用。我使用while循环以正确的方式解决这个问题吗?

采纳答案by thiton

The []operator in bash is syntactic sugar for a call to test, which is documented in man test. "or" is expressed by an infix -o, but you need an "and":

[]bash 中的运算符是调用 的语法糖test,记录在man test. “或”由中缀表示-o,但您需要一个“和”:

while [ $guess != 5 -a $guess != 10 ]; do

回答by Matvey Aksenov

There are 2 correct and portable ways to achieve what you want.
Good old shellsyntax:

有 2 种正确且可移植的方法来实现您想要的。
好的旧shell语法:

while [ "$guess" != 5 ] && [ "$guess" != 10 ]; do

And bashsyntax (as you specify):

bash语法(如您所指定):

while [[ "$guess" != 5 && "$guess" != 10 ]]; do

回答by tripleee

The portable and robust way is to use a casestatement instead. If you are not used to it, it might take a few looks just to wrap your head around the syntax.

可移植和健壮的方法是使用case语句代替。如果您不习惯它,可能需要多看几眼才能了解语法。

while true; do
    case $guess in 5 | 10) break ;; esac
    echo Your answer is $guess. This is incorrect. Please try again.
    echo -n "What is your guess? "
    read guess  # not $guess
done

I used while truebut you could in fact use the casestatement there directly. It gets hairy to read and maintain, though.

我使用过,while true但实际上您可以case直接在那里使用该语句。不过,阅读和维护起来会很麻烦。

while case $guess in 5 | 10) false;; *) true;; esac; do ...