Ubuntu – How to execute a task in background?

background-processcommand line

Is it possible to run a task or script started from terminal at the background?

Best Answer

There are multiple answers here, depending on what you want (this answer is valid in bash and zsh shells, others may vary).

If you need to run a command in background and you know it before running it, simply add a & at the end of the command (using sleep 60, do nothing during 1 minute, as example command):

[romano:~] % sleep 60 &
[1] 9054
1& [romano:~] %

If you have already run it, you can stop it with ctrl-Z, and when the shell gives you a prompt, you can background it with the command bg:

1& [romano:~] % sleep 60  
[1]  + 9084 suspended  sleep 60
1z [romano:~] 20 % bg
[1]  + 9084 continued  sleep 60
1& [romano:~] % 

In both cases, the process/job is still attached to your terminal; if you close your terminal a hangup (HUP) signal is sent to the process --- most process will gracefully exit then. If you need to ensure that the process will continue, you can either start it with:

nohup sleep 60 & 

or, after having sent it to background with bg or with a simple &, tell the shell to forget about it, with:

disown %% 

(%% is a job control shortcut, and here stands for the last process sent in background).

Then you have to take account of the output of the process --- in the first two cases the output will still arrive to the terminal; in the case of nohup it will be diverted on a file called nohup.out, and in the latter case (with disown) it will go to the terminal unless you close it, in which case the behavior is quite undefined. It is good practice to take care yourself of the output of a background process using redirection.

Related Question