bash 如何在陷阱命令后解除陷阱
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31201572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to untrap after a trap command
提问by gextra
I have an error trap as follows:
我有一个错误陷阱,如下所示:
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
}
There is a part of my code where I do expect an error:
我的代码中有一部分确实希望出现错误:
command1
command2
command3
set +e #deactivates error capture
command4_which_expects_error
set -e #re-activates error capture
command5
Overall I need to ignore the trap during the execution of command4_which_expects_error
总体而言,我需要在执行command4_which_expects_error期间忽略陷阱
The set +edoes not seem to disable the trap. Any other ways to "untrap" and then "re-trap" ?
该套+ E似乎并没有禁用的陷阱。还有其他方法可以“解除陷阱”然后“重新陷阱”吗?
回答by pedroapero
Here is what you can find in the trapmanual:
以下是您可以在陷阱手册中找到的内容:
The KornShell uses an ERR trap that is triggered whenever set -e would cause an exit.
KornShell 使用一个 ERR 陷阱,每当 set -e 导致退出时就会触发该陷阱。
That means it is not triggered by set -e
, but is executed in the same conditions. Adding set -e
to a trapon ERR would make your script exit after executing the trap.
这意味着它不是由 触发set -e
,而是在相同条件下执行。添加set -e
到ERR上的陷阱将使您的脚本在执行陷阱后退出。
To remove a trap, use:
要移除陷阱,请使用:
trap - [signal]
回答by ti7
To ignore the failure of a command that you know will fail, you can cause the line to always succeed by appending || true
.
要忽略您知道会失败的命令的失败,您可以通过附加|| true
.
Example:
例子:
#!/bin/bash
set -e
failed() {
echo "Trapped Failure"
}
trap failed ERR
echo "Beginning experiment"
false || true
echo "Proceeding to Normal Exit"
Results
结果
Beginning experiment
Proceeding to Normal Exit
回答by anubhava
You can use this trap
to reset trap
set earlier:
您可以使用它trap
来trap
更早地重置设置:
trap '' ERR