Linux Command Reference ยท Processes and Signals
Bash bg and fg commands
Reference for the Bash bg and fg builtins: resume a stopped job in the background, bring a job to the foreground, use job specs, Ctrl+Z and job control in scripts.
fg brings a job to the foreground: it becomes the program that owns your terminal again and receives keyboard input. bg resumes a stopped job but leaves it running in the background, so you get your prompt back. Together with Ctrl+Z (stop the foreground job) and & (start in the background) they make up shell job control.
Both are Bash builtins and work on jobs shown by jobs. Without an argument they act on the current job, the one marked +.
fg [JOBSPEC] bg [JOBSPEC...]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Syntax
fg [%N | %string | %?string | %% | %+ | %-] bg [JOBSPEC ...]
| Argument | Description |
|---|---|
| none | The current job (+ in the jobs list). |
%N |
Job number N. |
%string |
The job whose command starts with string. |
%?string |
The job whose command contains string. |
%- |
The previous job. |
Returns: fg returns the exit status of the job it brought forward. bg returns 0 unless the job does not exist or job control is disabled (bg: no job control).
Usage notes
- Job control must be on. Interactive shells have it by default. In a script
fgandbgfail withno job controluntil you runset -m. bgonly helps stopped jobs. A job that already runs in the background is unaffected. A job that reads from the terminal will stop again withSIGTTINas soon as it tries to read.- Typical flow: start something slow, press Ctrl+Z, type
bg, keep working. Laterfgto wait for it or interact with it. - Output keeps appearing. A background job still writes to your terminal. Redirect it (
cmd > log 2>&1 &) to keep the screen clean. fgand Ctrl+C. Once a job is in the foreground, Ctrl+C interrupts it; Ctrl+Z stops it again.- Different shell, different table. Another terminal cannot
fgyour job. - Detach completely with
disown(stop tracking the job) ornohup(ignore the hangup signal).
Related
jobs,wait,kill,nohup- Lessons: Jobs and background