Home / Using nohup to prevent processes stopping on disconnect

Using nohup to prevent processes stopping on disconnect

A long running process running on a Unix/Linux command line may stop running if you lose your SSH session. Using the "nohup" command will allow the command to keep running if you lose your connection or need to logout. This post looks at how to do this.

Previously I looked at how to use a counter in the PHP CLI for long running processes. Some of the scripts I ran myself were run with nohup so I could leave the counter outputting information, log off and go home. When I got home I was able to tail the output from the nohup.out file (see below) and see where the process was up to.

All you need to do is as follows:

nohup mycommand &

"nohup" is the nohup program which prevents "hangups" which means that if you decide you need to logoff the command being run (in this case "mycommand") will keep running. If your connection to the SSH server is broken then it will also continue to run.

"mycommand" in the above example is the name of the command you want to run.

And the & at the end of the line makes the process run in the background. Once the command starts you can then continue to issue other commands or logout if you so choose.

After executing the above command you’ll see this displayed on the command line, and you may need to press the <enter> key before being able to enter other commands:

nohup: appending output to `nohup.out'

This means that all the output from the command will go into a file called "nohup.out" in the current working directory. If you want to see the end of the output you can do this, which would show the last 10 lines of the nohup.out file:

tail nohup.out

If you want the output to continue showing on the command line as it is output to the file, use the -f flag which will continue to output the information from the nohup.out file as it is added to:

tail -f nohup.out

You can alternatively output the text from the command to a different file using redirection as shown in the example below, which would output the result into foo.txt instead of nohup.out:

nohup mycommand > foo.txt &

This won’t display the "appending output to" message and the command line is available again directly after you hit the <enter> key i.e. you won’t need to hit <enter> again.

That’s all there is to it. Use "nohup command &" and then you can log off and let the process continue running.