Bash While循环不结束

时间:2014-09-07 07:22:34

标签: linux bash while-loop

我正在玩bash编程。我写了一个简单的bash程序,它接受读者的输入。如果读者输入了字符串" bye" 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

如何修改代码以便程序可以进行多次输入?

3 个答案:

答案 0 :(得分:3)

inputString的条件下,while附加双引号。如果没有双引号,如果您的变量为空,则会引发错误。

更新

脚本上有拼写错误,在$之前添加inputString,进行变量替换:while [ "$inputString" != "bye" ]

答案 1 :(得分:2)

bash 4+中你也可以:

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

答案 2 :(得分:1)

在变量前面使用$来扩展它。 $ inputString

相关问题