【问题标题】:Mutiple conditions in OS X bash script WHILE loopOS X bash 脚本 WHILE 循环中的多个条件
【发布时间】:2014-10-30 06:59:24
【问题描述】:

基本上我想做的是从 std 输入中读取一个变量并检查该变量是 1 还是 2。如果不是,我想通知用户并再次询问,我认为 while 循环是有意义的(我在 bash shell 中使用 OS X Mavericks)

这适用于单一条件:

read result

while [[ "$result" != "1" ]];
do
echo $result
echo "You must enter 1 or 2. Please try again: "
read result
done
echo "success"

但是当我尝试做一个或条件时:

while [[ "$result" != "1" ]] || [[ "$result" != "2" ]];

如果我在终端中输入 1 或 2,这与输入的 1 或 2 不匹配。我也尝试过

while [[ "$result" != "1" ] || [ "$result" != "2" ]];

会产生语法错误。

while [[ "$result" != "1" || "$result" != "2" ]];

这也不匹配 1 或 2。 有谁知道正确的语法??

【问题讨论】:

    标签: bash shell while-loop osx-mavericks sh


    【解决方案1】:

    其实你需要使用&&(AND)而不是||,所以使用:

    while [[ "$result" != "1" && "$result" != "2" ]];
    

    这是因为您正在检查 $result 是否为 not 1 and not 2

    【讨论】:

    • 别担心,我们在编写代码时都会犯这些错误。
    • 是的,但是在 BASH 中可以使用不同的括号编写不止一种方法。
    猜你喜欢
    • 2013-03-10
    • 2015-04-04
    • 1970-01-01
    • 2019-12-10
    • 2023-04-06
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多