Home > database >  Why does "exit" not exit my script when I pipe it to "tee"?
Why does "exit" not exit my script when I pipe it to "tee"?

Time:08-15

I am running a script which is using tee to log the output to screen and also to a file:

{ echo "hello world" ; exit 1; } | tee -a logfile.log

The exit is not working. I can't exit my script. When I delete tee, it works. Why is that?

CodePudding user response:

It happens because the pipeline spawns a subshell for each component, so the exit runs inside this new shell.

You should rewrite the script like:

echo "hello world" | tee -a logfile.log
exit 1

CodePudding user response:

As covered elsewhere (including, somewhat indirectly, BashFAQ #24), pipelines create subshells, so your exit exits only the subshell.

You can avoid this by replacing the pipeline with a redirection to a process substitution:

{ echo "hello world"; exit 1; } > >(tee -a logfile.log)
  • Related