我有一个错误陷阱如下:
trap failed ERR
function failed {
local r=$?
set +o errtrace
set +o xtrace
echo "###############################################"
echo "ERROR: Failed to execute"
echo "###############################################"
# invokes cleanup
cleanup
exit $r
}
Run Code Online (Sandbox Code Playgroud)
我的代码中有一部分我预计会出现错误:
command1
command2
command3
set +e #deactivates error capture
command4_which_expects_error
set -e #re-activates error capture
command5
Run Code Online (Sandbox Code Playgroud)
总的来说,我需要在执行command4_which_expects_error时忽略陷阱
该套+ E似乎并没有禁用的陷阱.任何其他"解开"然后"重新陷阱"的方法?
ped*_*ero 31
您可以在陷阱手册中找到以下内容:
KornShell使用ERR陷阱,只要set -e导致退出,就会触发该陷阱.
这意味着它不会被触发set -e
,而是在相同的条件下执行.添加set -e
到陷阱的ERR执行陷阱后就会使你的脚本退出.
要删除陷阱,请使用:
trap - [signal]
Run Code Online (Sandbox Code Playgroud)
您可以使用它trap
来重置trap
设置:
trap '' ERR
Run Code Online (Sandbox Code Playgroud)
要忽略已知会失败的命令的失败,可以通过追加使行始终成功|| true
。
例:
#!/bin/bash
set -e
failed() {
echo "Trapped Failure"
}
trap failed ERR
echo "Beginning experiment"
false || true
echo "Proceeding to Normal Exit"
Run Code Online (Sandbox Code Playgroud)
结果
#!/bin/bash
set -e
failed() {
echo "Trapped Failure"
}
trap failed ERR
echo "Beginning experiment"
false || true
echo "Proceeding to Normal Exit"
Run Code Online (Sandbox Code Playgroud)