BASH中的错误处理 [英] Error handling in BASH
问题描述
什么是你最喜欢的方法BASH来处理错误?
我已经在网络上发现了BASH处理错误的最好的例子是在 http://www.linuxcommand.org 书面威廉Shotts,JR >。
What is your favorite method to handle errors in BASH? The best example of handling errors in BASH I have found on the web was written by William Shotts, Jr at http://www.linuxcommand.org.
威廉Shotts,JR建议使用下面的函数用于错误处理BASH:
William Shotts, Jr 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
将在出口删除,当前行号将被打印出来。 (设置-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 some caveats).
您可以让中断调用错误
你(在这种情况下,它使用默认的1退出code和无消息),或调用它自己,提供明确的价值;例如:
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屋!