4

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

0

4 Answers 4

9

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  
^Z
[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.

5

add & to the command.

Example:

$ cp FromA ToB &
2

This example will run updates in the background:

sudo apt-get dist-upgrade -y &

Just note the singe &.
If you want to hide the stdout, do following:

sudo apt-get dist-upgrade -y > /dev/null &
2

If you want it more advanced, and want to be able to use the session later locally or by SSH, you can use screen.

# screen
# apt-get update -y

Then press CTRL+A followed by D.

Later you can reattach:

# screen -rd
1
  • This was very clear & helpful.
    – avia
    Jul 9, 2021 at 0:05

Not the answer you're looking for? Browse other questions tagged .