Bash while循环,如何读取输入直到条件为false

时间:2014-03-06 17:09:16

标签: bash

我一直遇到运行时错误。我在OSX的终端上运行它。错误是,

test.sh: line 15: while[!false]: command not found
test.sh: line 16: syntax error near unexpected token `do'
test.sh: line 16: `do'

由于我刚开始编写bash脚本,我无法弄清楚我在语法上的错误。

ipa build &
TASK_PID=$!
sleep 5
kill $TASK_PID

finished=false
declare -a schemes

echo "*****************************************************************************************"
echo "| View the list of available build configs above."
echo "| Enter the name of the build you want,one at a time."
echo "| Type \"done\" to finish entering scheme names"
echo "*****************************************************************************************"

while[!${finished}]
do
read input
  if[$input == "done"]
  then
      finished=true
  else
  schemes=("${schemes[@]}" $input)
  echo ${schemes[0]}
  fi
done

echo "Do you want a verbose build? (y/n)"
read verbose


echo "Building your selected schemes....."
ipa build -s ${schemes[0]}

3 个答案:

答案 0 :(得分:10)

truefalse不是bash中的布尔关键字;它们只是字符串(以及命令的名称;稍后会详细介绍)。即使您通过在必要时提供空格来修复语法:

while ! [ "${finished}" ]; do
    ...
done

这个循环永远不会运行。为什么? finished的值是true还是false,它只是一个非空字符串。此代码将运行[命令(是的,它是一个命令,而不是语法)并成功,因为它的参数是非空字符串。 !否定它,因此while循环的条件总是失败。

最直接的解决方法是明确地将$finished与字符串“true”进行比较。

while [ "$finished" != "true" ]; do
   ...
done

我提到truefalse也是命令:true总是成功,false总是失败。通常情况下,你不想做我要建议的事情,但这里没关系,因为truefalse就像你想象的一样简单的一对命令。

finished=false
while ! $finished; do
    ...
    # At some point
    finished=true
done

在这里,我们让$finished扩展为命令的名称,然后执行该命令并使其退出状态由!取消。只要finished=false,否定的退出状态始终为0,而​​while循环将继续运行。更改finished的值后,否定的退出状态将为1,循环将退出。

答案 1 :(得分:6)

在测试条件下在括号周围留出空间

while [ ! ${finished} ]

&安培;

if [ $input = "done" ]

答案 2 :(得分:0)

为什么不尝试这样的事情:

#!/bin/bash

list='Foo Bar Baz Quux Xyzzy QUIT'

select item in $list; do
    case $item in
    QUIT)
        break
        ;;
    *)
        echo "You picked '$item'!"
        ;;
    esac
done