Skip to content

Background jobs: &, jobs, fg and Ctrl+Z

IntermediateLesson 27 of 667 min

Run a program in the background with &, list jobs, bring one back with fg, pause it with Ctrl+Z and stop it with Ctrl+C. Practise with a pretend web server.

Some programs keep running until you stop them: a web server, a long copy, ping. While one runs in the foreground, it holds the terminal and you can't type another command.

A handy example is Python's small web server, which shares the folder you're in with other computers on your network:

cd share
python3 -m http.server 8000

It holds the terminal until you press Ctrl+C, which stops it.

& runs it in the background

Put & at the end and the program runs in the background: the prompt comes straight back. The shell prints the job's number and its PID, as in [1] 5000.

python3 -m http.server 8000 &
jobs
Command or keyDoes
jobslists the jobs started from this terminal
fgbrings a job back to the foreground (fg %2 for job 2)
Ctrl+Zpauses the foreground program and gives you the prompt
bglets a paused job carry on in the background
kill %1stops job 1

Forgot the &? Press Ctrl+Z, then type bg. Same result.

Tip:Background jobs belong to this terminal: close it and they stop too.

Your turn

Share the share folder: go into it and start python3 -m http.server 8000 in the background. List your jobs, and check the server answers with curl http://localhost:8000/. Then bring it to the foreground with fg and stop it with Ctrl+C.

Next