jobs
jobs / bg / fg
Interactive job control: jobs lists background/stopped jobs, bg resumes a stopped job in the background, fg brings it to the foreground. Jobs are addressed with %N, %+, %-, or %string.
jobs [-lnprs] [JOBSPEC] | bg [JOBSPEC] | fg [JOBSPEC] Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| jobs -l | Include PIDs in the listing |
| jobs -p | Print only PIDs |
| %N | Refer to job number N |
| %+ / %% | Current job (most recently backgrounded) |
| %- | Previous job |
| Ctrl-Z | Stop the foreground job (SIGTSTP) — then bg or fg it |
Examples
sleep 60 & jobs Backgrounds a sleep; jobs shows [1]+ Running.
fg %1 Bring job 1 to the foreground.
sleep 30 # Ctrl-Z, then: bg Stop the foreground sleep, then resume it in the background.
jobs -p | xargs kill Kill every background job of this shell.
Gotcha
Job control usually requires an interactive shell — scripts get 'no job control' unless started with 'set -m'. Job numbers are shell-local and get reused as jobs finish; store PIDs via $! for reliable tracking.
Related
wait
Blocks until specified background jobs or PIDs complete, returning the exit status of the last one waited for. Essential for scripts that launch parallel background work and need to synchronize.
trap
Registers a command to run when the shell receives a signal or special event (EXIT, ERR, DEBUG, RETURN). The workhorse for cleanup handlers, temp-file removal, and error diagnostics in scripts.
set (options)
Changes shell option flags and/or replaces positional parameters. The 'safer bash' idiom 'set -euo pipefail' is the most common use — it turns on error-exit, unset-variable-error, and pipeline failure propagation.