Description
We could implement a crude, multiline regex scanner to warn on the use of traps in concert with exec, which presents a hazard. The script author should be made aware that traps do not persist into exec environments.
Related: koalaman/shellcheck#2631
Frankly, trap is such an unwieldy tool that we may even recommend against writing reusable traps and recommend instead the use of <failable command> || <backup command>
and/or if [ ! <failable command> ]; then ... fi
.
Instead of subshells, the script author can redirect output to a file, then read the file back.
Sadly, the simple die
/ panic
command is unavailable in most shells.
Another hazard of traps is that many authors forget to implement them for conditions other than EXIT. Ultimately, it may be prudent to recommend rewriting a script with any traps, in a more competent application language such as Go or Ruby. We can then use a simple, single line regex to scan for uncommented
arbitrary indentation, trap commands.
Note the more common interpolated subshells "$(...)"
and backticks, whose failure may not trigger the desired traps.
Note that zsh function traps still present a conflict with exec, and require a separate, multiline regex to detect. (Though two single line regexes used in tandem will be more efficient.)
That leaves parenthesis subshells as the last trigger for warnings, when not prefixed by a string interpolation dollar sign. That includes nested subshells within larger string interpolation. Anyway, subshells should trigger warnings when list traps are used, unless the interpreter is zsh, or bash with set -E enabled.