简体   繁体   English

使用RETURN陷阱进行bash清理并立即重置处理程序

[英]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: 它具有几个不错的功能:

  1. The trap is set up before creating the directory, so there is no race condition. 陷阱是创建目录之前设置的,因此没有竞争条件。
  2. Creating a directory means I shouldn't need any more mktemp calls in the script, because I can just put everything in that directory. 创建目录意味着不需要在脚本中进行任何mktemp调用,因为我可以将所有内容放入该目录中。
  3. Creating a directory rather than a file gives a better security baseline, because it's common that everyone can see what's directly in /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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM