我正在尝试实现一个错误处理程序。它是一个帮助程序,用于检查变量中是否存在错误代码$?
并使用代码和消息退出脚本。
下面的代码非常简单且不言自明,但它不起作用,我根本无法理解发生了什么。我试过$?
作为参数传递给这个函数,但它也不起作用。我错过了什么?
#!/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
...