Skip to content

fg Command Cheat Sheet

fg (foreground) resumes a suspended or background job in the current shell and brings it to the foreground, allowing you to interact with it again.


Synopsis

fg [JOB_SPEC]

Understanding Job Control

When you run commands in a shell: - Foreground: The command takes over the terminal (e.g., vim, top). You cannot run other commands until it finishes or you suspend it. - Background: The command runs asynchronously (e.g., cp large_file dest &). You get your prompt back immediately. - Suspended: The command is paused (usually via Ctrl+Z).

fg is the tool to bring background/suspended jobs back to your control.


Basic Usage

Resume Most Recent Job

If you have suspended a job (Ctrl+Z) or started one in background (&), simple fg brings the last one back.

fg

Resume Specific Job

First, list jobs to find the ID.

jobs
Output:
[1]-  Stopped                 vim myfile.txt
[2]+  Stopped                 top
- +: Current job (default for fg) - -: Previous job

Resume job 1 (vim):

fg %1

Using % Shortcuts

You don't always need the full command.

  • %1: Job 1
  • %% or %+: Current job
  • %-: Previous job
  • %string: Job whose command starts with "string"
  • %?string: Job whose command contains "string"

fg %vim
(Resumes the job starting with "vim")


Workflow Examples

1. Suspending and Resuming

  1. Start a long process: ping google.com
  2. Realize you need the terminal: Press Ctrl+Z
    [1]+  Stopped                 ping google.com
    
  3. Do other work: ls -la
  4. Resume ping: fg

2. Moving Background to Foreground

  1. Start a script in background:
    ./backup.sh &
    # [1] 12345
    
  2. Decide you want to watch it or provide input:
    fg %1
    

fg vs bg

  • fg: Brings job to foreground (interactive, takes over terminal).
  • bg: Resumes a suspended job in the background (runs silently).

Example: You launched tar -czf backup.tar.gz /home but forgot the &. 1. Ctrl+Z (Pause it) 2. bg (Continue it in background) 3. (Later) fg (Bring it back to check on it)


Pitfalls

  • Output Noise: If a background job prints to stdout/stderr, it will mess up your current shell display. fg fixes this by giving it full control again.
  • Hangups: If you close the terminal, background jobs might be killed (unless you used nohup or disown).

Exit Status

Code Meaning
0 Success
1 No such job (if job ID is invalid)

Notes

  • fg is a shell builtin (like cd, alias). It is not a separate executable file.
  • It only works for jobs started in the current shell session. You cannot fg a process started in another terminal window.