Job control lets one terminal juggle several commands. Each command line you start is a job, even if it is a pipeline of several processes.
Foreground and background
A foreground job holds the terminal until it finishes. Add & to run it in the background, and you get the prompt back at once:
$ sleep 300 &
[1] 7001[1] is the job number and 7001 is the process ID. Background jobs can still print to your screen, so redirect output if it gets noisy:
./build.sh > build.log 2>&1 &Listing jobs
$ sleep 400 &
[2] 7002
$ jobs -l
[1]- 7001 Running sleep 300 &
[2]+ 7002 Running sleep 400 &The + marks the current job, which fg and bg use when you give no number. The - marks the previous one. Job numbers belong to this shell only; another terminal has its own list.
Pause, resume, move
Press Ctrl+Z to stop the foreground job. It stays in memory but does not run.
Then you can choose where it continues:
$ sleep 500
^Z
[3]+ Stopped sleep 500
$ bg %3
[3]+ sleep 500 &
$ fg %3
sleep 500bg resumes a stopped job in the background. fg brings a job to the foreground. %3 means job 3.
To end a job, use kill %3, or bring it forward and press Ctrl+C.
If a background job tries to read from the terminal, it is stopped until you bring it to the foreground.
Leaving the shell
Background jobs are still attached to your session. If the terminal disconnects, they may receive SIGHUP and end. Two common protections:
nohup ./long-task.sh &or, for a Bash job that is already running:
disown %1nohup makes the command ignore the hangup signal. disown removes the job from the shell's table, so Bash will not pass SIGHUP on to it. disown does not redirect the job's output, so redirect it when you start the command. For work you want to return to, tmux or screen are better.
Try it
Start sleep 200, press Ctrl+Z, run jobs, resume it with bg, then end it with kill %1 (use the number jobs shows). The processes and cron lab lets you practise freely.
Check your understanding
Job control
All 5 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.