Bash – Why `> the.log 2>&1 &` causes the job to sustain log out

bashgnu-screenio-redirectionnohup

I use

myscript > my.log 2>&1 &

to run a script and collect it's output – so that when I logout – the script will still be running. It I were to start it with myscript & – it will be terminated right after logout.

But that's a strange effect: all that > my.log 2>&1 & does is redirect stderr to stdout…

Why > my.log 2>&1 & causes the job to sustain log out?

Best Answer

Normally if you put something in the background it will continue to run even after its parent shell exits. In fact, I can create a test case like this:

/bin/sh -c 'while true; do echo hi; sleep 5; done' &

and then exit the shell and using ps I can see it's still running, forever, until I kill it.

There is one difference between redirecting the output and not: if you don't redirect the output and you exit your shell, then the stdout/stderr file descriptors are closed and the next time you try to write to them the write operation will fail. If your script is checking for that, or running with the -e (exit on error) option set, then your script will stop. Compare the behavior of the above with this version:

/bin/sh -c 'while true; do echo hi || exit 1; sleep 5; done' &

or

/bin/sh -ec 'while true; do echo hi; sleep 5; done' &

If you leave this running, exit the shell, and use ps you'll see that when it tries to run the echo it will fail, and exit.

If you were to redirect the output to a file then obviously the write will not fail anymore and the script will continue to run.

Related Question