Question

Without arguments trap prints the currently set commands for all traps. However, a subshell does not inherit traps, so the canonical example for saving and restoring traps fails in bash:

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

The trap on the RHS of the assignment runs in a subshell, so save_traps is always the empty string. Other than writing the output of trap to a temporary file, how can a script find the current command set for a trap?

Was it helpful?

Solution

Works for me.

Create a sample trap:

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

Store the trap into save_traps:

$ save_traps=$(trap)

Remove:

$ trap SIGIO
$ trap | wc -l
   0

Restore:

$ 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.

OTHER TIPS

Although the Bash manpage seems to say that traps are reset in subshells, and command substitution is executed in a subshell, running trap inside $() works anyway (tested in Bash 3.2 and 4.2). It is also mentioned in POSIX that traps=$(trap) should work.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top