如果您希望能够处理错误而不是盲目退出,而不是使用 set -e
,请trap
在ERR
伪信号上使用a 。
#!/bin/bash
f () {
errorCode=$? # 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 $errorCode # 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信号以及其他Bash伪信号RETURN
和DEBUG
。