我正在尝试实现一个错误处理程序。它是一个辅助程序,用于检查变量中是否有错误代码$?
,并使用代码和消息退出脚本。
下面的代码非常简单,一目了然,但它不起作用,我完全不明白发生了什么。我试过将其$?
作为参数传递给此函数,但它也不起作用。我遗漏了什么?
#!/bin/bash
#this line causes error "asd: command not found"
asd
exit_if_error () {
ERROR_STATUS="$1"
ERROR_TEXT="$2"
if [ "$?" != "0" ]; then
# prints an error message on standard error and terminates the script with an exit status
echo "$ERROR_TEXT" 1>&2
exit "$ERROR_STATUS"
fi
}
exit_if_error "1" "Something bad happened"
echo "No errors during execution"
这也行不通
#!/bin/bash
#this line causes error "asd: command not found"
asd
exit_if_error () {
ERROR="$1"
ERROR_STATUS="$2"
ERROR_TEXT="$3"
if [ "$ERROR" != "0" ]; then
# prints an error message on standard error and terminates the script with an exit status of 1
echo "$ERROR_TEXT" 1>&2
exit "$ERROR_STATUS"
fi
}
exit_if_error "$?" "1" "Something bad happened"
echo "No errors during execution"
您如何处理脚本中的错误?您写过类似的代码吗?我只是想找到一个不太冗长的解决方案。
command_a
if [ "$?" != "0" ]; then
echo "command_a failed..." 1>&2
exit 1
fi
command_b
if [ "$?" != "0" ]; then
echo "command_b failed..." 1>&2
exit 1
fi
...
答案1
您需要用 来trap
拦截错误信号。
#!/bin/bash
ERROR=0
error_handling(){
((ERROR > 0)) &&
printf %s\ %s\\n "$1" "$2"
exit $ERROR
}
trap "ERROR=1" ERR
jdshfsduoifh
error_handling 1 "PANIC error!"
Bash 具有处理缺失命令的内置函数
#!/bin/bash
command_not_found_handle(){
echo "Command '$@' not found, please install me!"
}
jdshfsduoifh
如果您确实想使消息静音,您可以将 stderr 重定向至/dev/null
。
#!/bin/bash
exec 3>&2 2>/dev/null
# This error will be
# redirected to /dev/null
ls nonexistant_1
(($? > 0)) &&
echo "Error: this isn't right!"
# Let's restore our old descriptor.
exec 2>&3 3>&-
ls nonexistant_2
exit
Stderr 可能已经分配了一个描述符;例如script.sh 2> file.log
,使用 exec 来操作当前 shell 的描述符,我们首先需要将 stderr 复制到一个新的描述符,然后再分配/dev/null
给 stderr,它允许恢复旧的描述符。