2013-12-12 104 views
1

如何在子shell命令失敗時終止shell。如何在子shell命令失敗時終止一個shell?

例如:

check(){ 
    if [ $1 -eq $1 2> /dev/null ]; then 
     echo "returning 0" 
     return 0 
    else 
     echo "returning 1" 
     return 1 
    fi 
} 

if [ "($check $1)" == 1 ]; then 
    echo "Error: with proper message" 
    exit 
fi 

if [ "$1" -le 1000 ] || [ "$2" -ge 10000 ]; then 
    echo "Error:" 
    exit 
fi 

我在這裏傳遞字符串和第一,如果條件失敗,並且如果第二條件與在命令行錯誤執行「整數表達預期」。 我知道()子shell命令失敗,但外殼沒有終止。如何在子shell命令失敗時從shell中退出。

回答

1

您想要測試函數的退出狀態。如下:

if [ "($check $1)" == 1 ]; then 

可能會導致錯誤。即使你說:

if [ "$(check $1)" == 1 ]; then 

,不會比較退出狀態,即返回值的函數。它會將功能的輸出1進行比較。

您將需要說調用你的函數:

check $1 

,然後說檢查退出狀態:

if [ $? -ne 0 ]; then 
    echo "Error: with proper message" 
    exit 
fi 

(沒有就這裏涉及任何子shell我可以看到。)

+0

感謝您的信息.. – Shriram