1 year ago
#350641
LetMeSOThat4U
Traps in bash with exec in a script
I want to accomplish two goals in a bash script:
- redirect output of a running script to a file and display it to the user at the same time
- execute two "cleanup" traps on exit and Ctrl-C
So I have this code:
IO_LOG="io_stats_$(date_hm).log"
ST_LOG="stress_test_$(date_hm).log"
# redirect script output to a log
exec &> >(tee -a "$ST_LOG" >&1)
# track disk io use with iotop running in background
/usr/sbin/iotop -botk &>"$IO_LOG" &
# kill iotop on exit of the main script (where this code is located)
trap 'kill $(jobs -p)' EXIT
# remove io log on sigint
trap "rm -fv \"$IO_LOG\"" SIGINT
# do the testing while iotop is tracking disk io
custom_long_running_stress_test_program
# (normal exit)
Before adding exec &>...
both traps ran reliably.
However, after adding it the trap of SIGINT
doesn't seem to run.
Now, I verified empirically that EXIT
trap works as intended, because it kills iotop
process even when redirecting output of the main script to a file with exec
. Background iotop
doesn't die when the EXIT
trap is commented out, with or without redirection and it is killed when it's on, again with or without output redirection (I wanted to make absolutely sure it works as intended in all four cases).
It's different with SIGINT trap:
- with redirection on the IO_LOG is not removed
- with redirection off the IO_LOG is removed (and
rm -fv
prints the name of the file)
Why is that? How can I make operation of SIGINT
trap work as intended?
bash
shell
scripting
interrupt-handling
0 Answers
Your Answer