This is a very specific question, but I am interested to know what causes this behaviour
Observed
Run the following command and trigger "CTRl-C" signal after the fist wait echo.
bash -c "trap 'echo trapped' EXIT; until false &>/dev/null; do echo 'Waiting...'; sleep 3; done" | tee /tmp/test.txt
Notice the following error:
^Cbash: line 1: echo: write error: Broken pipe
Now run the following command and do the same:
bash -c "trap 'echo trapped' EXIT; until false &>/dev/null; do echo 'Waiting...'; sleep 3; done" | tee -i /tmp/test.txt
Notice how there is no error and the trap message is correctly shown.
Question
What would cause this behaviour and why does it seem that I need to use the -i/--ignore-interrupts
option in order to correctly support trapping with tee
?
Specs
- GNU bash, version 5.1.12(1)-release
CodePudding user response:
What causes CTRL-C trap echo to fail when using
tee
It told you:
write error: Broken pipe
Because tee
terminated, Bash can't write data to the pipe, which causes it to fail.
no
--ignore-interrupts
?
Because tee is not closed, Bash can write data to the pipe, so it does not exit.
What would cause this behaviour
Typing ctrl c or sending SIGINT woudl cause tee to terminate, closing the pipe, and making Bash unable to send any more data to the pipe. As you do. (?)
why does it seem that I need to use the -i/--ignore-interrupts option in order to correctly support trapping with tee?
The statement in the question is false. The trap is executed, it just does not print the requested text, because the pipe is closed. the trap actually prints bash: line 1: echo: write error: Broken pipe
error message.
I believe you meant to write the error to another file descriptor:
bash -xc "trap 'echo trapped >&2' ...
Also use set -x
to debug your scripts, as above.
until null
is super odd - just while true
or while :
. There is no command named null
, you could do until false
but that's like double negation.