【问题标题】:Bash script - While condition with if/then [duplicate]Bash脚本-带有if / then的While条件[重复]
【发布时间】:2017-04-17 11:43:14
【问题描述】:

所以我在理解如何循环条件时遇到了问题。这是我的例子:

#!/bin/bash
echo " Which team do you prefer, FSU or UF?"
read -r TEAM
while [ "$TEAM" != "FSU" || "UF" ]; do
        echo "That was not one of your choices. Please choose FSU or UF"
if [ "$TEAM" == "FSU" ]; then
        echo "You chose the better team"
else [ "$TEAM" == "UF" ];
        echo "You did NOT choose the better team"
fi
done

基本上,我正在寻找的是用户输入,如果不满足该条件,它将循环返回,直到满足正确的输入。 我究竟做错了什么?在此示例中,如果我选择 FSU 或 Uf 之外的输入作为:

"./test.sh:第 4 行:[:缺少 `]' ./test.sh: 第 4 行: UF: command not found"

但是,如果我选择 FSU 或 UF,我会得到同样的错误。

【问题讨论】:

  • [ "$TEAM" != "FSU" || "UF" ] 不是有效的语法。您必须将 $TEAM 与每个可能的字符串进行比较
  • 主要问题是 while 行应该是 while [ "$TEAM" != "FSU" || "$TEAM" != "UF" ]; do。除此之外,您在错误的地方终止了循环 (done)。
  • 第三,看this page,你的if子句的结果似乎也倒退了。

标签: bash if-statement while-loop


【解决方案1】:

固定脚本:

#!/bin/bash
echo " Which team do you prefer, FSU or UF?"
read -r TEAM
while [[ "$TEAM" != "FSU" && "$TEAM" !=  "UF" ]]; do
        echo "That was not one of your choices. Please choose FSU or UF"
        read -r TEAM
done
if [[ "$TEAM" == "FSU" ]]; then
        echo "You chose the better team"
else [[ "$TEAM" == "UF" ]];
        echo "You did NOT choose the better team"
fi

变化:

查看Done位置,用户输入验证通过后需要退出while loop

在用户输入失败后,您需要询问用户的输入。因此read -r TEAMwhile loop 中。

您的逻辑比较是OR,而不是while loop 中的AND

【讨论】:

  • 好的。那个工作。谢谢。另一个网站上的其他人告诉我,您将在 while 循环中嵌入 if/then/else 语句。我正在尝试,但它不起作用。所以,我写的脚本和你的有点不同,但它仍然有效。我没有在 if/then/else 语句中加双括号。
  • 你可以这样做,这取决于你的情况,如果你想让if else 在每个while loop 上得到验证,你把它放在你的loop block 中,但这不是我们现在想要的.
猜你喜欢
  • 2021-08-10
  • 1970-01-01
  • 2020-11-11
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 2014-12-16
  • 1970-01-01
相关资源
最近更新 更多