如果您希望能够处理错误而不是盲目退出,而不是使用set -e
,请在ERR
伪信号上使用trap
。
#!/bin/bash
f() {
errcode=$? # save the exit code as the first thing done in the trap function
echo "error $errorcode"
echo "the command executing at the time of the error was"
echo "$BASH_COMMAND"
echo "on line ${BASH_LINENO[0]}"
# do some error handling, cleanup, logging, notification
# $BASH_COMMAND contains the command that was being executed at the time of the trap
# ${BASH_LINENO[0]} contains the line number in the script of that command
# exit the script or return to try again, etc.
exit $errcode # or use some other value or do return instead
}
trap f ERR
# do some stuff
false # returns 1 so it triggers the trap
# maybe do some other stuff
其它陷阱可以被设置为处理其他信号,包括普通的Unix信号加上其它击伪信号RETURN
和DEBUG
。
如果你喜欢的ABS,你一定会喜欢的[BashGuide(http://mywiki.wooledge.org/BashGuide),[BashFAQ]( http://mywiki.wooledge.org/BashFAQ)和[BashPitfalls](http://mywiki.wooledge.org/BashPitfalls)。 – 2010-12-08 04:45:12