【问题标题】:Comparing Strings in Bash with Logical Or将 Bash 中的字符串与逻辑或进行比较
【发布时间】:2014-07-15 14:20:27
【问题描述】:

我在处理一个简单的y/n 问题时遇到了问题。考虑以下代码:

 echo "Hi there"
 read ans
 if [[ $ans != "y" || $ans != "Y" || $ans != "YES" || $ans != "yes" ]]; then
      echo "Foo"
      exit 0
 fi

我已经看过——我会争辩——一些关于 StackOverflow 的信息更丰富的答案以寻求建议:Simple logical operators in Bash

我尝试了所有不同类型的变体,例如:

if [[ ($ans != "y" || $ans != "Y" || $ans != "YES" || $ans != "yes") ]]; then
    echo "Foo"
    exit 0
fi

if [[ ($ans != "y*" || $ans != "Y*" || $ans != "YES*" || $ans != "yes*") ]]; then
    echo "Foo"
    exit 0
fi

if [[ ($ans != "y") || ($ans != "Y") || ($ans != "YES") || ($ans != "yes") ]]; then
    echo "Foo"
    exit 0
fi

无论我为什么在这些情况下输入,它都会自动失败,我不知道为什么。如果有人有更好的方法来处理 y/n 答案,请告诉我!理想情况下,我想使用模式匹配(就像我可能使用 Perl 一样),但我不完全确定完成简单 y/n 问题的最佳方式/最有效方式。

【问题讨论】:

    标签: bash if-statement conditional


    【解决方案1】:

    您需要使用&& 而不是||。就目前而言,如果它不等于 any 这些可能性,则执行“then”块。你的意思是说如果它不等于all,那么执行“then”块。这需要&&

    【讨论】:

    • 掌心...一定是介于太晚或太早之间。当 SO 允许我这样做时,我会将其作为答案
    【解决方案2】:

    你可以使用:

    echo "Hi there"
    read ans
    case "$ans" in
        y|Y|YES|yes)
            ;;
    
        *)
          echo "Foo"
          exit 0
          ;;
    esac
    

    【讨论】:

    • 很好,但我只需要处理一个案例。
    【解决方案3】:

    逻辑需要调整:

    echo "Hi there"
    read ans
    if ! [[ "$ans" == "y" || "$ans" == "Y" || "$ans" == "YES" || "$ans" == "yes" ]]; then
         echo "Foo"  # User answered no
         exit 0
    fi
    

    只有当答案不是“y”、“Y”或“YES”之一时,才会回显“Foo”。相比之下,考虑原始逻辑:

    [[ $ans != "y" || $ans != "Y" || $ans != "YES" || $ans != "yes" ]]
    

    无论用户的答案是什么,这些测试中至少有一个是正确的。

    使用case 语句

    您可以考虑使用case 语句来分析用户的回答:

    read -p "Hi there: " ans
    case "$ans" in
        [yY]*) ;;
        [nN]*) echo "Foo" ; exit 0 ;;
        *) echo "You were supposed to answer yes or no" ;;
    esac
    

    【讨论】:

      【解决方案4】:

      试试read ans,而不是read $ans

      【讨论】:

      • 我的错,它在我的脚本中是正确的,但不是在这里。我会改变的
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-17
      • 2021-03-08
      • 2014-04-07
      • 2010-12-24
      • 2015-08-14
      • 2021-09-09
      • 2020-10-27
      相关资源
      最近更新 更多