2014-12-28 48 views
3

下面是我的shell脚本。如何在while循环条件块中比较函数的退出状态?无论我从check1函数返回我的代码进入while循环在bash脚本中,如何在while循环条件中调用函数

#!/bin/sh 
    check1() 
    { 
      return 1 
    } 

    while [ check1 ] 
    do 
      echo $? 
      check1 
      if [ $? -eq 0 ]; then 
        echo "Called" 
      else 
        echo "DD" 
      fi 
      sleep 5 
    done 

回答

8

删除test命令 - 也被称为[。所以:从Bourne和POSIX壳得到

while check1 
do 
    # Loop while check1 is successful (returns 0) 

    if check1 
    then 
     echo 'check1 was successful' 
    fi 

done 

壳条件语句后执行命令。一种看待它的方法是,whileif测试成功或失败,而不是真或假(尽管true被认为是成功的)。

顺便说一句,如果你必须明确地测试$?(这是不是经常需要),然后(Bash中)的(())结构通常更容易阅读,如:

if (($? == 0)) 
then 
    echo 'worked' 
fi 
7

由函数(或命令)执行返回的值存储在$?一个解决办法是:

check1 
while [ $? -eq 1 ] 
do 
    # ... 
    check1 
done 

一个更好和更简单的解决方案可以是:

while ! check1 
do 
    # ... 
done 

在这种形式中零为真和非零是假的,例如:

# the command true always exits with value 0 
# the next loop is infinite 
while true 
    do 
    # ... 

您可以使用!否定值:

# the body of the next if is never executed 
if ! true 
then 
    # ... 
+2

您也可以考虑'直到'而不是'while!' – cdarke