How to Run Linux Commands or Shell Scripts in Background



When we run a command in the terminal, it will be executed on the same terminal and we have to wait or open a new session to continue our work. 
This is called running the command in the foreground or foreground process. 

A background process is a process/command that is started from a terminal and runs in the background, without interaction from the user.

Run a Linux Command in the Background

To run a command in the background, add the ampersand symbol (&) at the end of the command:


command &


The shell job ID (surrounded with brackets) and process ID will be printed on the terminal:

[1] 3507

You can have multiple processes running in the background at the same time.


The background process will continue to write messages to the terminal from which we invoked the command. To suppress the stdout and stderr messages use the following syntax:

command > /dev/null 2>&1 & 

>/dev/null 2>&1 means redirect stdout to /dev/null and stderr to stdout .


Display the running jobs in the Terminal

To display the status of all stopped and background jobs in the current shell session run the below command:

jobs -l

The output includes the job number, process ID, job state, and the command that started the job:

[1]+ 3507 Running                 ping google.com &
[2]+ 2787 Running                 /bin/bash ./while_infinite_loop.sh /dev/null 2>&1 &

To bring a background process to the foreground, use the fg command:

fg

If we have multiple background jobs, include % and the job ID after the command:


fg %1

To terminate the background process, use kill command followed by the process ID:

kill -9 3507

Move a Foreground Process to Background


To move a running foreground process in the background:

Stop the process by typing Ctrl+Z.
Move the stopped process to the background by typing bg.


To Keep Background Processes Running After a Shell Exits
Now if we close the putty or terminal session, or connection is lost then the background job will be lost.

First Method

Remove the job from the shell’s job control using the disown shell builtin:

disown

If we have more than one background jobs, include % and the job ID after the command:

disown %1

Confirm that the job is removed from the table of active jobs using the jobs -l command. 

To list all running processes, including the disowned use the ps aux command.

ps aux |grep -i command
 
Second Method

The nohup command executes another program specified as its argument and ignores all SIGHUP (hangup) signals. SIGHUP is a signal that is sent to a process when its controlling terminal is closed.

To run a command in the background using the nohup command, type:

nohup command &

The command output is redirected to the nohup.out file.

nohup: ignoring input and appending output to 'nohup.out'

If we log out or close the terminal, the process is not terminated.





If you like please follow and comment