如何让我的shell脚本在出错时中止?

时间:2012-06-26 05:49:17

标签: bash shell

例如我有

make test
# do other stuff

'make test'运行一些单元测试,并将成功或错误退出。如果make test中止错误,我该如何终止整个脚本并显示一条消息?

2 个答案:

答案 0 :(得分:3)

make test || exit $?

在一般情况下,set -e强制脚本中止任何错误;但这通常是矫枉过正,因为你必须防止无关紧要的错误。

答案 1 :(得分:2)

没有错误消息,您只需使用

set -e
make test
#more stuff

如果要打印状态

make test
if [ "$?" = "0" ]; then
    echo "all fine!"
else
    echo "yikes, something went wrong"
    exit 1
fi
#more stuff