← All lessons
Processes and scripts · Lesson 2 of 7

Background jobs

Normally the shell waits for a command to finish. Put & at the end and it runs in the background instead, so you get the prompt straight back while it works. The shell prints a job number in brackets and the PID.

$ tar czf big.tar.gz photos/ &
[1] 5120
$ jobs
[1]+  Running    tar czf big.tar.gz photos/ &

If you start something in the foreground and wish you hadn't, press Ctrl+Z. That pauses (suspends) it and gives you the prompt. Then bg lets it carry on in the background, or fg brings it back to the foreground. With several jobs, use the number: fg %2.

jobs lists this shell's jobs. They belong to the terminal, so closing the terminal normally stops them. To keep a job running after you log out, start it with nohup (no hang-up): nohup ./long-task.sh &. Its output goes to a file called nohup.out.

For anything you'll come back to over SSH, tmux or screen are worth learning: they keep a whole terminal session alive on the server, and you can reattach to it later from anywhere.

Practice

Run ./build.sh in the background.

More info

Quick reference

cmd &Run in the background.
Ctrl+ZPause the foreground job.
bg, fg, fg %NResume in background; bring to front.
jobsList this shell's jobs.
nohup cmd &Keep running after logout.
tmux, screenSessions you can leave and come back to.

The other Linux courses