Restore traps without a temporary file

With no arguments, trap prints the current specified commands for all traps. However, the subshell does not inherit traps, so the canonical example of saving and restoring traps does not work in bash:

  save_traps = $ (trap)
 ...
 eval "$ save_traps"

The destination RHS trap is executed in a subshell, so save_traps is always an empty string. Besides writing trap output to a temporary file, how can a script find the current set of commands for a trap?

+4
source share
2 answers

It works for me.

Create a test trap:

 $ trap $ trap echo SIGIO $ trap trap -- 'echo' SIGIO 

Keep trap in save_traps :

 $ save_traps=$(trap) 

Delete

 $ trap SIGIO $ trap | wc -l 0 

Recovery:

 $ eval "$save_traps" $ trap trap -- 'echo' SIGIO 

Tested with

 $ bash --version GNU bash, version 3.2.48(1)-release (x86_64-apple-darwin12) Copyright (C) 2007 Free Software Foundation, Inc. 
+3
source

Although the Bash page mask seems to say that the traps are reset in the subhelps and the subroutine substitution is done in a subshell, the trap inside $() works anyway (tested in Bash 3.2 and 4.2), POSIX also mentions that traps=$(trap) should work.

Thanks to pgas on #bash at irc.freenode.net .

+1
source

Source: https://habr.com/ru/post/1400400/


All Articles