Search code examples
bashhttp-redirectnohup

Difference between nohup vs simple output redirect


What is the difference between the following methods of launching background jobs?

  • ./long_job.sh > logfile &
  • nohup ./long_job.sh > logfile &

(by default, option 2 this will print to nohup.out or you can redirect to a filename of your choice).

What are the advantages of nohup? I tested the following shell script as a proxy for long_job.sh and exited the terminal (with ctrl-D)

while [ 1==1 ]; do
    jot -r -c 4 A Z | rs -g  0 4
    echo $$ # Echo pid
    sleep 2
done

There is a nohup question with similar title, but it asks about difference between redirection of stdout and stderr

EDIT: This question does not talk about explicit file redirect. Without redirect, when shell quits, the child process dies because it does not have stdout to print to. But with redirect it does not need the shell window to be open. Operationally, both approaches above achieve the same outcome (which is run the job even after terminal closes). My question about was the difference between the two approaches.


Solution

  • The difference in the listed approaches depends on the status of huponexit variable in your shell. The status of this variable is obtained by shopt | grep huponexit.

    When huponexit is off, the listed approaches are operationally identical -- Both redirect standard output to logfile and continue to run upon exiting the shell.

    When huponexit is on, (shopt -s huponexit), the shell sends the hangup (hup) signal to child processes which causes it to terminate. The nohup approach continues to work.

    Since you may not always have privileges to control huponexit, the nohup approach is more failsafe for long background jobs.