【问题标题】:checking two conditions using while loop in bash script在 bash 脚本中使用 while 循环检查两个条件
【发布时间】:2015-04-04 15:52:08
【问题描述】:

我想检查用户是否输入了“y”或“n”,如果没有,则继续循环要求用户输入正确的字母,但它不起作用......下面的代码显示了我所拥有的到目前为止尝试过....有人可以帮帮我吗???

echo "Enter 'y' to exit or 'n' to continue" 
echo -n "Do you want to exit? "
read character

while [ "$character" != "y" || "$character" != "n" ];
do

    echo -n "Wrong key re-enter 'y' to exit or 'n' to continue"
    read character
done

【问题讨论】:

  • $var != y || $var != n总是为真。任何不是y 的东西都会使第一部分为真,y 将使第二部分为真。
  • 那么,我该如何让它为假呢
  • 想想你要测试的逻辑。你想要$var 不是x OR 不是y?或者你想要$var 不是x AND 不是y
  • 你能和我谈谈不同之处吗,因为现在我对我想要它做什么有点困惑.....抱歉
  • 在你的代码中也使用ShellCheck

标签: bash while-loop conditional-statements multiple-conditions


【解决方案1】:

你可以:

while [[ $(read -sn1 character; echo ${character^^})  =~ [^YN] ]]; do
  echo -n "Wrong key ..."
done   
  • 你会想要 -s 除非你想要回显键
  • 您将需要 -n1 将输入限制为一个字符
  • 您还可以通过 $? 检查 ctrl+c 和 ctrl+d 是否按下? (ctrl-d 为 1,ctrl+c 为 130,但 ctrl+d 仅在包含 -e 标志并使用 readline 时才有效)
  • 如果需要,您也可以在其中包含一个提示,而且,您不必使用“$character”,您可以什么都不给它并检查 $REPLY
  • 如果您真的不想按 ctrl+c,请考虑使用陷阱

【讨论】:

    【解决方案2】:

    非常感谢大家...经过良好的坚持和韧性,我终于找到了我正在寻找的答案... A贴出以下代码:

    #if the user's input is not Y or N
    while [[ $(read -sn1; echo ${character^^})  =~ [^YN] ]];
    do
        echo -n "Re-enter 'y' to exit or 'n'to continue: ?"
        read character
    done 
    

    【讨论】:

      【解决方案3】:

      这种方法试图考虑更多的用户可能性,并且仍然完成同样的事情。

      #if the user's input is not Y or N, Yes or No, y or n, yes or no
      while [[ ! "$character" =~ ^([yY][eE][sS]|[yY])$ ]] && [[ ! "$character" =~ ^([nN][oO]|[nN])$ ]]
      do
          echo -n "Wrong key re-enter 'y' to exit or 'n' to continue"
          read character
      done
      

      【讨论】:

        猜你喜欢
        • 2013-03-10
        • 1970-01-01
        • 2016-03-06
        • 2014-10-30
        • 2017-04-03
        • 2020-11-11
        • 2022-10-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多