Thursday, January 26, 2012

Unix Nohup: Run a Command or Shell-Script Even after You Logout


When you execute a Unix job in the background ( using &, bg command), and logout from the session, your process will get killed. You can avoid this using several methods — executing the job with nohup, or making it as batch job using at, batch or cron command.

This quick tip is for beginners. If you’ve been using nohup for a while, leave us a comment and tell us under what situations you use nohup.
In this quick tip, let us review how to make your process running even after you logout, using nohup.
Nohup stands for no hang up, which can be executed as shown below.
nohup syntax:
# nohup command-with-options &
Nohup is very helpful when you have to execute a shell-script or command that take a long time to finish. In that case, you don’t want to be connected to the shell and waiting for the command to complete. Instead, execute it with nohup, exit the shell and continue with your other work.

Explanation about nohup.out file

By default, the standard output will be redirected to nohup.out file in the current directory. And the standard error will be redirected to stdout, thus it will also go to nohup.out. So, your nohup.out will contain both standard output and error messages from the script that you’ve executed using nohup command.
Instead of using nohup.out, you can also redirect the output to a file using the normal shell redirections.

Example: Printing lines to both standard output & standard error

while(true)
do
echo "standard output"
echo "standard error" 1>&2
sleep 1;
done

Execute the script without redirection

$ nohup sh custom-script.sh &
[1] 12034
$ nohup: ignoring input and appending output to `nohup.out'

$ tail -f nohup.out
standard output
standard error
standard output
standard error
..

Execute the script with redirection

$ nohup sh custom-script.sh > custom-out.log &
[1] 11069
$ nohup: ignoring input and redirecting stderr to stdout

$ tail -f custom-out.log
standard output
standard error
standard output
standard error
..
If you log-out of the shell and login again, you’ll still see the custom-script.sh running in the background.
$ ps aux | grep sathiya
sathiya  12034  0.0  0.1   4912  1080 pts/2    S    14:10   0:00 sh custom-script.sh