[英]bash cleanup with RETURN trap and resetting handler immediately
Is there a way to disable a trap within the trap handler? 有没有办法在陷阱处理程序中禁用陷阱?
I'd like to simplify some code by using the RETURN trap. 我想通过使用RETURN陷阱来简化一些代码。 my_func will return the value of my_command.
my_func将返回my_command的值。 The tmpfile will be cleaned up as my_func returns.
当my_func返回时,tmpfile将被清除。 This technique would allow me to avoid assigning a temp var to hold $?
这种技术将使我避免分配临时变量来保存$? from my_func while I do cleanup.
从my_func进行清理时。
However, I'm unable to reset the trap handler within the handler and cleanup is now invoked after every function return. 但是,我无法在处理程序中重置陷阱处理程序,并且现在在每次函数返回后都调用清除操作。
Ultimately what I really want to do is cleanup after my_command is invoked but still have it as the last command so the return value is implicit. 最终,我真正想做的是在调用my_command之后进行清理,但仍将其作为最后一个命令,因此返回值是隐式的。 Any suggested alternatives would be appreciated.
任何建议的替代方案将不胜感激。
cleanup() { # generic cleanup w/ reset
"$@"
trap - RETURN
}
my_func() {
local -r tmpfile="/tmp/tmpfile"
trap "cleanup rm ${tmpfile}" RETURN
my_command -f ${tmpfile}
}
caller() {
if my_func ; then
do_success_ops
fi
}
I always use this pattern: 我总是使用这种模式:
trap 'rm -rf "$workspace"' EXIT
workspace="$(mktemp --directory)" # Or -d
# Use $workspace
This has several nice features: 它具有几个不错的功能:
mktemp
calls in the script, because I can just put everything in that directory. mktemp
调用,因为我可以将所有内容放入该目录中。 /tmp
, but a new directory will be owned by you and will be created "u+rwx, minus umask restrictions" (from man mktemp
). /tmp
直接包含的内容,但是新目录将归您所有,并创建为“ u + rwx,减去umask限制”(从man mktemp
)。 If you want to clean up earlier I would recommend just doing it explicitly. 如果您想更早进行清理,我建议您明确地进行清理。 Your solution has two unnecessary levels of indirection: the trap and the passing of arguments to be run.
您的解决方案有两个不必要的间接级别:陷阱和要运行的参数传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.