Running process in the background

Solution 1: Nohup and ampersand

$ myscript.sh &

The ampersand “&” tells the shell to run the script in the background. You will get the prompt back. But as the script is still a child of the shell. In other words, if you terminate the shell, the script will terminate as well.

To overcome this you may want to use the command “nohup” which ignore the HUP Termination signals. The output will be sent to the “nohup.out” in the current directory

$ nohup myscript.sh &

Alternatively, you may want to redirect to the standard output to standard error to /dev/null

$ nohub myscript.sh  > /dev/null 2>&1 &

The issue is that you cannot interact with the script once it has started.

Solution 2: Screen

There is a post written by me on Basic GNU Screen Usage on CentOS which you might want to read for more information.

You may want to use screen to run a shell. You may want to name a screen session

$ screen -S my_preferred_screen_name -m

You can also list running Screen Session

$ screen -ls
There is a screen on:
2109.myScreenA (Detached)
1 Socket in /var/run/screen/S-user1

To reattach the Screen Session

screen -r 2109

To detach from a screen session. [Press ctrl with “a” and “d” together]

Ctrl-a + d

Solution 3: tmux

If you prefer to use tmux. You may want to take a look at A beginner’s guide to tmux for more information. If you are starting a session

$ tmux new ./myscript.sh

If you are detaching a session

$ tmux new -d ./myscript.sh

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s