Bash 中的错误处理 [英] Error handling in Bash
问题描述
你最喜欢用什么方法来处理 Bash 中的错误?我在网络上发现的处理错误的最佳示例是 William Shotts, Jr 在 http://www.linuxcommand.org 上编写的.
What is your favorite method to handle errors in Bash? The best example of handling errors I have found on the web was written by William Shotts, Jr at http://www.linuxcommand.org.
他建议在 Bash 中使用以下函数进行错误处理:
He suggests using the following function for error handling in 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 脚本中是否有更好的错误处理例程?
Do you have a better error handling routine that you use in Bash scripts?
推荐答案
使用陷阱!
tempfiles=( )
cleanup() {
rm -f "${tempfiles[@]}"
}
trap cleanup 0
error() {
local parent_lineno="$1"
local message="$2"
local code="${3:-1}"
if [[ -n "$message" ]] ; then
echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}"
else
echo "Error on or near line ${parent_lineno}; exiting with status ${code}"
fi
exit "${code}"
}
trap 'error ${LINENO}' ERR
...然后,每当您创建临时文件时:
...then, whenever you create a temporary file:
temp_foo="$(mktemp -t foobar.XXXXXX)"
tempfiles+=( "$temp_foo" )
和 $temp_foo
将在退出时被删除,并打印当前行号.(set -e
同样会给你退出错误行为,虽然它来了有严重的警告并削弱代码的可预测性和可移植性).
and $temp_foo
will be deleted on exit, and the current line number will be printed. (set -e
will likewise give you exit-on-error behavior, though it comes with serious caveats and weakens code's predictability and portability).
您可以让陷阱为您调用 error
(在这种情况下,它使用默认退出代码 1 并且没有消息)或自己调用它并提供显式值;例如:
You can either let the trap call error
for you (in which case it uses the default exit code of 1 and no message) or call it yourself and provide explicit values; for instance:
error ${LINENO} "the foobar failed" 2
将以状态 2 退出,并给出明确的消息.
will exit with status 2, and give an explicit message.
这篇关于Bash 中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!