On Wed, Apr 13, 2022 at 7:59 AM Frank Heckenbach <f.heckenb...@fh-soft.de> wrote: > This script writes "foo" to bar rather than stdout as I'd expect. > > It's triggered by the "if" statement (which doesn't even cause > running in a subshell, so it's not that). > > #!/bin/bash > set -e > trap 'echo foo' 0 > #false > bar # "foo" written to stdout correctly > if true; then false; else false; fi > bar # "foo" written to bar
I don't believe this is a bug, though Chet is welcome to chime in with an authoritative answer. The script exits after the else clause because false returns 1 and errexit is set. At this point in the program stdout has been redirect to the file bar, so when the trap echos to stdout its content goes to bar as well. I don't see anything in the docs about traps resetting their output file descriptors before they are ran. To work around this you need to save the original stdout file descriptor. Something like this: #!/bin/bash exec {STDOUT}>&1 exec {STDERR}>&2 set -e trap 'echo foo >&${STDOUT}' EXIT if true; then false; else false; fi >bar