How To Run A ShellScript in background

You can do shell script run in background using following steps.

nohup and disown a process

As standard, when a login shell exits, it sends a HUP (hangup) signal to all of its children. The effect of this is that all background tasks terminate when their interactive login shell terminates. bash can get around this with the huponexit shell option, but the standard way to deal with this in advance is to use the nohup (no-hangup) command. nohup ensures that the task does not get terminated when its owning shell exits, which can be particularly useful for long-running tasks; it is nice to be able to connect to a system, kick off a task, and disconnect again immediately. Without nohup, you would have to keep that interactive login shell active, which means ensuring that the network con- nectivity remains and that the machine you are connected from stays up and does not lose power, crash, or for any other reason end your interactive session.

Using below nohup and & you can run a shell script or a command in background even after you logout from the shell prompt.

Here 2>&1 does redirect of all your stdout and stdin to the specified log file, here its mirror.log

$ nohup /usr/local/bin/ > /var/tmp/mirror.log 2>&1 &

[1] 14322

$ cat /var/tmp/mirror.log

Wed Mar 16 22:27:31 GMT 2011: Starting to resync disk mirrors. Do not interrupt this process.

$ exit


Connection to node3 closed.

Related to nohup is disown; a command already running can be disowned in the same way that a nohup process is automatically disowned.

node1$ sleep 500 &

[1] 29342

node1$ disown %1 node1$ exit logout

Connection to node1 closed. node7:~$ ssh node1

[email protected] node1's password:

Linux node1 2.6.26-2-amd64 #1 SMP Sun Jun 20 20:16:30 UTC 2010 x86_64

Last login: Wed Mar 16 22:30:50 2011 from node1$ ps -eaf|grep sleep

steve    29342     1 0 22:30 ?     00:00:00 sleep 500 

In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.