【问题标题】:While loop not equal command not found未找到while循环不等于命令
【发布时间】:2014-05-03 03:38:01
【问题描述】:

我正在尝试执行一个简单的 while 循环,将变量与字符串进行比较。它无法加载此行的错误。错误状态 [: missing `]' 和 : command not found。我的 while 循环看起来像;

mainMenuInput = ""
while ["$mainMenuInput" != "Q" || "$mainMenuInput" != "q"]
do

【问题讨论】:

    标签: linux bash variables while-loop


    【解决方案1】:

    如果您使用的是 bash,我认为正确的语法是:

        while [ $variable -ne "q" || $variable -ne "Q" ];
    

    【讨论】:

      【解决方案2】:

      有几个错误:

      mainMenuInput="" 
      while [ "$mainMenuInput" != "Q" ] && [ "$mainMenuInput" != "q" ]
      

      看到变量声明确实需要像var=value。否则,bash 会解释为您要使用 =value 作为参数来执行 var 命令:

      mainMenuInput="" 
                   ^
                   no spaces around =
      

      while 中,您需要在括号周围放置空格。另外请注意,您需要使用&&(和)而不是||(或),否则它永远不会退出while

      while [ "$mainMenuInput" != "Q" ] && [ "$mainMenuInput" != "q" ]
             ^                          ^^                          ^
         space                   it has to be AND               space
      

      事实上,条件可以改写为:

      while [[ "$mainMenuInput" != [qQ] ]]
      

      【讨论】:

      • -o而不是||-a而不是&&,当在[]中使用时
      • 谢谢,@herby,但 POSIX 建议使用 && 和 ||在 -a 和 -o 上使用单括号表示法。
      • 非常感谢大家,我不知道您必须在“=”周围没有空格谢谢。我现在需要它吗谢谢。 @herby using -o 也确实可以显示感谢的内容。
      • @Seatter 变量使用var=value 表达式设置,= 周围没有任何空格。否则,bash 将解释您要使用 =value 参数执行 var 命令。
      猜你喜欢
      • 2023-03-30
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 2019-12-07
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多