【问题标题】:Using "and" in Bash while loop在 Bash while 循环中使用“and”
【发布时间】:2019-07-08 11:49:42
【问题描述】:

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

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!"

我要改变的是这一行:

while [ $guess != 5 ]; do

这样的:

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

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

【问题讨论】:

  • 问题标题原本是“or”而不是“and”。当然,根据德摩根定律,无论您将要求表述为“我想要 5 或 10”还是双重否定“我不想要一个不是 5 和不是 10 的答案”,这在逻辑上都是一样的.

标签: linux bash


【解决方案1】:

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

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

bash 语法(如您指定):

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

【讨论】:

  • 感谢您抽出宝贵时间告诉我,我注意到现在我没有将这两个陈述括起来,这就是它不起作用的原因。
【解决方案2】:

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

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

【讨论】:

  • 是的,我的错误“和”是我应该使用的。这将解释为什么“-o”在我之前尝试时不起作用;当它给我一个错误时,我只是认为它仅适用于 if 语句。非常感谢您的及时回复!
  • 注意:这不是 POSIX,因此不可移植。
【解决方案3】:

可移植且健壮的方法是改用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

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

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

【讨论】:

    猜你喜欢
    • 2019-11-22
    • 2013-12-20
    • 1970-01-01
    • 2023-03-08
    • 2017-08-31
    • 2013-03-22
    • 1970-01-01
    • 2013-05-05
    • 2018-02-01
    相关资源
    最近更新 更多