运行以下代码:
#!/bin/bash
set -o pipefail
set -o errtrace
set -o nounset
set -o errexit
function err_handler ()
{
local error_code="$?"
echo "TRAP!"
echo "error code: $error_code"
exit
}
trap err_handler ERR
echo "wrong command in if statement"
if xsxsxsxs
then
echo "if result is true"
else
echo "if result is false"
fi
echo -e "\nwrong command directly"
xsxsxsxs
exit
产生以下输出:
wrong command in if statement
trap.sh: line 21: xsxsxsxs: command not found
if result is false
wrong command directly
trap.sh: line 29: xsxsxsxs: command not found
TRAP!
error code: 127
我怎样才能捕获'找不到命令' if 语句中也有错误?
你不能在 if 中捕获 ERR 测试
来自 bash 人:
The ERR trap is not executed if the failed command
is part of the command list immediately following a while or
until keyword, part of the test in an if statement, part of a
command executed in a && or || list, or if the command's return
value is being inverted via !
但你可以改变这个
if xsxsxsxs
then ..
to this
xsxsxsxs
if [[ $? -eq 0 ]]
then ..
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)