2008-12-15 77 views
28

假設shell腳本(/ bin/sh或/ bin/bash)包含多個命令。如果任何命令有失敗的退出狀態,我該如何幹淨地讓腳本終止?顯然,可以使用塊和/或回調,但是有更清晰,更簡潔的方法嗎?使用& &也不是一個真正的選項,因爲命令可能很長,或者腳本可能有不重要的東西,如循環和條件。Shell腳本:死於任何錯誤

回答

52

隨着標準shbash,你可以

set -e 

它將

$ help set 
... 
     -e Exit immediately if a command exits with a non-zero status. 

它也可以(從我可以收集)與zsh。它也應該適用於任何Bourne shell後代。

隨着csh/tcsh,你必須與#!/bin/csh -e

+0

謝謝,這似乎是我想要的。我應該銳化我的Google fu,我猜... :) – Pistos 2008-12-15 15:56:19

+3

請注意,條件中的命令可能會失敗,而不會導致腳本退出 - 這是至關重要的。例如:如果grep something/some/where;那麼:它被發現了;其他:沒有找到;無論在/ some/where中是否找到某物,fi都能正常工作。 – 2008-12-16 04:00:48

+0

你說「標準sh」。這是否意味着它是POSIX?編輯:我查了它,這是POSIX:http://pubs.opengroup.org/onlinepubs/009695399/utilities/set.html – Taywee 2015-12-28 21:36:04

16

啓動腳本可能是你可以使用:

$ <any_command> || exit 1 
0

您可以檢查$?看到最近的退出代碼是什麼..

e.g

#!/bin/sh 
# A Tidier approach 

check_errs() 
{ 
    # Function. Parameter 1 is the return code 
    # Para. 2 is text to display on failure. 
    if [ "${1}" -ne "0" ]; then 
    echo "ERROR # ${1} : ${2}" 
    # as a bonus, make our script exit with the right error code. 
    exit ${1} 
    fi 
} 

### main script starts here ### 

grep "^${1}:" /etc/passwd > /dev/null 2>&1 
check_errs $? "User ${1} not found in /etc/passwd" 
USERNAME=`grep "^${1}:" /etc/passwd|cut -d":" -f1` 
check_errs $? "Cut returned an error" 
echo "USERNAME: $USERNAME" 
check_errs $? "echo returned an error - very strange!"