2014-12-28 50 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