【问题标题】:While loop in OR condition not working. BASH shellOR 条件下的 while 循环不起作用。 BASH 外壳
【发布时间】:2016-11-27 18:39:01
【问题描述】:

我正在尝试在 OS X 终端中运行 shell 脚本。只要您输入 m 或 a,程序就会终止。

问题是,我无法让 OR 语句工作。

#!/bin/sh
read File

while [ "$File" != "m" ] || [ "$File" != "a" ]
do
read File
done

当我这样做的时候

while [ "$File" != "m" ]

它工作得很好。我尝试了多种方法,例如

while test $File != "m" || test $File != "a"
while test $File != "m" -o test $File != "a"
while [ $File != "m" -o $File != "a" ]

它们似乎都不起作用。 当用户输入“m”或

时,我发布的上述代码不会停止循环

【问题讨论】:

  • 您可能想要&& 而不是||。您现在使用的条件将始终评估为真,因为如果任一替代方案评估为假,则另一个肯定评估为真。换句话说,你的逻辑是可疑的。
  • 这个构造也很奇怪。将其写为 while read File; do if test "$File" = m || "$file" = a; then break; fi ... 会更简洁。您当前的构造不会检查是否有任何 read 失败,因此当输入流终止时它会表现得很奇怪。

标签: bash shell input while-loop boolean


【解决方案1】:

我建议更换

while [ "$File" != "m" ] || [ "$File" != "a" ]

通过

while [ "$File" != "m" ] && [ "$File" != "a" ]

until [ "$File" = "m" ] || [ "$File" = "a" ]

或使用正则表达式(bash):

while [[ ! $File =~ m|a ]]

从 bash 中查看:help until

【讨论】:

    猜你喜欢
    • 2018-01-21
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2019-11-26
    • 1970-01-01
    相关资源
    最近更新 更多