I'm implementing the logging solution presented here, and I don't know if the following lines are required whenever I exit the parent Bash process/script:

if [ -n "$teepid" ]; then
    exec 1>&- 2>&-  # Close file descriptors to signal EOF to the `tee`
                    # command in the background process
    wait $teepid # Wait for background process to exit

Those lines can be found in the log() function and in the end of the script. I know that they're required in the log() function, but are they required at the end of the script?

In other words: Would my background job exit nicely without having the aforementioned code written before every exit command in my parent process?


The process identified by PID $teepid is backgrounded using &. If you exit without waiting for that PID to finish, the only bad thing that will happen is the same thing that happens if you use & in the shell. You'll hit [Enter] at some later point and get pestered with a [1] {pid} exited (or something similar, can't remember precisely now) message before your next prompt line is displayed.

  • "If you exit without waiting for that PID to finish, the only bad thing that will happen is the same thing that happens if you use & in the shell." - What it means? – Dor Jul 15 '11 at 11:12
  • Try entering echo "hello" & from a shell prompt, hit ENTER twice, and you'll see what I mean. – LawrenceC Jul 15 '11 at 13:03
  • 1
    Sorry to come to the party late (and uninvited), but I believe you’re mistaken. In my experience, processes are aware of only their own children. If a shell script detaches a subprocess, the script’s parent process (commonly an interactive shell) has no knowledge of that (sub)process, and will not know when it terminates. – Scott Feb 16 '13 at 1:00
  • 1
    You can demonstrate this quickly and easily by typing (echo "hello" &) –– the parentheses force the creation of a new process even before the echo "hello" & is interpreted, and then that, of course, forks a process at yet another level –– simulating the scenario of a script starting an asynchronous subprocess. Another good illustration: (sleep 42 &) and then wait –– you’ll get your shell prompt back immediately, but a ps will show that the sleep is still in the background. – Scott Feb 16 '13 at 1:03
  • 1
    The problem/risk, however, that if this logging script doesn’t wait for the tee processes to finish, then you might get your shell prompt back before the tee finishes, and so you might get output from the tee (which is output from the script) displayed after the shell prompt is displayed. If it’s more than a line or two, it’s very easy for the user not to see the shell prompt, and therefore to assume that the script is still running, when, in fact, it is done. – Scott Feb 16 '13 at 1:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.