【问题标题】:Bash While loop Not EndingBash While 循环未结束
【发布时间】:2014-10-31 17:07:54
【问题描述】:

我在玩 bash 编程。我编写了一个简单的 bash 程序,它接受读者的输入。如果读者键入字符串“再见”,则 while 循环结束。所以程序很简单我写了这样的东西

#!/bin/sh
inputString="hello"
while [ inputString != "bye" ]
do
    echo "Please write something (bye to quit)"
    read inputString
    echo "You typed : ${inputString}"
done

在用户一次输入两个单词之前,它可以完美运行。

如果用户输入类似这样的内容

bye bye

程序崩溃并出现以下错误

./WhileLoop.sh: 5: [: bye: unexpected operator

如何修改代码,使程序可以接受多个输入?

【问题讨论】:

标签: linux bash while-loop


【解决方案1】:

while 的条件下,在inputString 周围加上双引号。没有双引号,如果你的变量为空,就会报错。

更新:

脚本有错别字,在inputString前加$,进行变量替换:while [ "$inputString" != "bye" ]

【讨论】:

  • 这是正确的答案。我需要的只是将 $inputString 放入双引号
  • @sadasidha 不,这不是正确答案。引用的"inputString" 与引用的"$inputString" 不同。所以,是的,需要引用,但需要把$放在前面。请只标记真正正确的答案。
  • @jm666 我认为缺少$ 是问题中的错字,因为发布的代码不会产生给定的错误。 (它只会永远循环,因为两个文字字符串永远不会彼此相等。)
【解决方案2】:

bash4+你还可以:

while read -r -p 'Please write something (bye to quit)>' ans
do
   echo "your answer =$ans="
   #convert the $ans to lowercase to match "BYE"
   #use matching to match "bye bye" or "byeanythinghere"
   #in case of double [[ don't needed the "", but never harm, so using it
   [[ "${ans,,}" =~ bye.* ]] && exit 0
   #[[ ${ans,,} =~ bye.* ]] && exit 0   #works too
   echo "not bye - yet"
done

【讨论】:

  • 仅供参考,,, 运算符需要 bash 4。
  • @chepner 永远不记得什么是新旧知识...我有 4.3 ;) 已编辑。
  • 当 Mac OS X 卡在 3.2 上时会有所帮助 :)
【解决方案3】:

在变量前面使用 $ 来扩展它。 $输入字符串

【讨论】:

  • 不,如果我这样写 while 循环,问题仍然存在 while [ $inputString != "bye" ]
猜你喜欢
  • 1970-01-01
  • 2020-02-15
  • 2012-10-04
  • 1970-01-01
  • 2014-04-20
  • 2019-03-15
  • 2016-02-08
  • 1970-01-01
相关资源
最近更新 更多