79645810

Date: 2025-05-30 16:38:36
Score: 1
Natty:
Report link

@The manpage (appears best documentation for Bash traps) says:

trap [-lp] [[arg] sigspec ...] The command arg is to be read and executed when the shell receives signal(s) sigspec.

If arg is absent (and there is a single sigspec) or -, each specified signal is reset to its original disposition (the value it had upon entrance to the shell). If arg is the null string the signal specified by each sigspec is ignored by the shell and by the commands it invokes.

If arg is not present and -p has been supplied, then the trap commands associated with each sigspec are displayed.

The best I came with now is:

$ cat -n tst.sh
     1  #!/usr/bin/env bash
     2
     3  trap err_handler ERR
     4  trap debug_handler DEBUG
     5
     6  err_handler() {
     7          printf 'ERR trapped in %s, line %d\n' "${FUNCNAME[1]}" "$BASH_LINENO"
     8  }
     9
    10  debug_handler() {
    11          err_handler_aside=$(trap -p ERR)
    12          trap - ERR
    13
    14          printf 'DEBUG trapped in %s, line %d\n' "${FUNCNAME[1]}" "$BASH_LINENO"
    15
    16          false
    17
    18          $err_handler_aside
    19  }
    20
    21  false
    22  false

This works as the false in the debug_handler does not get trapped, but the handler will handle the second false in main again:

$ ./tst.sh
DEBUG trapped in main, line 21
DEBUG trapped in main, line 21
ERR trapped in main, line 21
DEBUG trapped in main, line 22
DEBUG trapped in main, line 22
ERR trapped in main, line 22

Thanks @EdMorton for tidying this up.

Reasons:
  • Blacklisted phrase (0.5): Thanks
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @EdMorton
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: Albert Camu