你最喜欢在Bash中处理错误的方法是什么?
我在网上找到的处理错误的最好的例子是William Shotts, Jr在http://www.linuxcommand.org上写的。
他建议在Bash中使用以下函数进行错误处理:
#!/bin/bash
# A slicker error handling routine
# I put a variable in my scripts named PROGNAME which
# holds the name of the program being run. You can get this
# value from the first item on the command line ($0).
# Reference: This was copied from <http://www.linuxcommand.org/wss0150.php>
PROGNAME=$(basename $0)
function error_exit
{
# ----------------------------------------------------------------
# Function for exit due to fatal program error
# Accepts 1 argument:
# string containing descriptive error message
# ----------------------------------------------------------------
echo "${PROGNAME}: ${1:-"Unknown Error"}" 1>&2
exit 1
}
# Example call of the error_exit function. Note the inclusion
# of the LINENO environment variable. It contains the current
# line number.
echo "Example of error with line number and message"
error_exit "$LINENO: An error has occurred."
在Bash脚本中是否有更好的错误处理例程?
另一个需要考虑的问题是返回的退出码。只有“1”是相当标准的,尽管bash本身使用了少数保留的退出码,并且同一页认为用户定义的代码应该在64-113范围内,以符合C/ c++标准。
你也可以考虑使用位向量方法,挂载使用它的退出码:
0 success
1 incorrect invocation or permissions
2 system error (out of memory, cannot fork, no more loop devices)
4 internal mount bug or missing nfs support in mount
8 user interrupt
16 problems writing or locking /etc/mtab
32 mount failure
64 some mount succeeded
OR-ing代码可以让脚本显示多个同时发生的错误。
这个功能最近对我很有用:
action () {
# Test if the first parameter is non-zero
# and return straight away if so
if test $1 -ne 0
then
return $1
fi
# Discard the control parameter
# and execute the rest
shift 1
"$@"
local status=$?
# Test the exit status of the command run
# and display an error message on failure
if test ${status} -ne 0
then
echo Command \""$@"\" failed >&2
fi
return ${status}
}
可以通过将0或最后一个返回值附加到要运行的命令的名称来调用它,这样就可以连接命令,而不必检查错误值。使用this,这个语句块:
command1 param1 param2 param3...
command2 param1 param2 param3...
command3 param1 param2 param3...
command4 param1 param2 param3...
command5 param1 param2 param3...
command6 param1 param2 param3...
变成这样:
action 0 command1 param1 param2 param3...
action $? command2 param1 param2 param3...
action $? command3 param1 param2 param3...
action $? command4 param1 param2 param3...
action $? command5 param1 param2 param3...
action $? command6 param1 param2 param3...
<<<Error-handling code here>>>
如果任何命令失败,错误代码将被简单地传递到块的末尾。我发现当您不希望在之前的命令失败后执行后续命令,但也不希望脚本立即退出(例如,在循环中)时,它很有用。