Managing Jobs with jobs, fg, and bg

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 137 of 205

A job is a command line that the shell is tracking: a single command, a pipeline, or a group started from one line. In an interactive shell, Bash keeps a job table of everything you started in the background or stopped with Ctrl + Z, and gives three built-in commands to work with it:

  • jobs lists the jobs in the table and their state.
  • fg brings a job to the foreground, where it receives the keyboard and the shell waits for it.
  • bg resumes a stopped job in the background, where it keeps running while you use the prompt.

Together with Ctrl + Z, these commands let you pause a program, run something else, and come back to it, or move a long task out of the way without restarting it. This feature is called job control. It is on by default in interactive shells and off in scripts, which changes what these commands can do there.

All terminal sessions in this lesson were run in a real interactive Bash 5.2 shell. The prompt is shown as $, and ^Z, ^C and ^D mark where Ctrl + Z, Ctrl + C and Ctrl + D were pressed. The PIDs will differ on your system.

Job States: Running, Stopped, Done

A job is in one of a few states:

StateMeaning
Runningthe job is executing, in the background (or in the foreground, though then you see no prompt)
Stoppedthe job is paused by a signal such as SIGTSTP (Ctrl + Z); it keeps its memory and position but uses no CPU
Donethe job finished with status 0; Exit N is shown for other statuses
Terminated, Killed, ...the job was ended by a signal

Pressing Ctrl + Z while a foreground command runs sends it SIGTSTP. The program stops, Bash takes back the terminal, adds the job to the table and prints its state:

$ sleep 100 &
[1] 555
$ sleep 200 &
[2] 556
$ sleep 300
^Z
[3]+  Stopped                 sleep 300

Two sleep commands were started in the background, and a third was started in the foreground and stopped. A stopped job is not finished: it is frozen until something resumes it.

Listing Jobs with jobs

jobs prints one line per job:

$ jobs
[1]   Running                 sleep 100 &
[2]-  Running                 sleep 200 &
[3]+  Stopped                 sleep 300

Each line shows:

  • The job number in brackets. Job numbers are local to this shell and are not the same as process IDs. They start at 1 and are reused once the table is empty.
  • A marker: + is the current job, the one fg and bg use when you give no argument. - is the previous job, which becomes current if the current one ends. The current job is normally the one most recently stopped or, if none is stopped, the one most recently started in the background.
  • The state and the command, with & at the end for jobs running in the background.

Options select or change what is printed:

$ jobs -l
[1]    555 Running                 sleep 100 &
[2]-   556 Running                 sleep 200 &
[3]+   557 Stopped                 sleep 300
$ jobs -p
555
556
557
$ jobs -r
[1]   Running                 sleep 100 &
[2]-  Running                 sleep 200 &
$ jobs -s
[3]+  Stopped                 sleep 300
OptionEffect
-ladds the process ID (for a pipeline, every process of the pipeline)
-pprints only the process IDs, one per line, which is convenient for other commands
-ronly running jobs
-sonly stopped jobs
-nonly jobs whose state changed since you were last told about them

jobs -n reports a change once. The first call after starting a job showed it; an immediate second call printed nothing:

$ sleep 30 &
[1] 572
$ jobs -n
[1]+  Running                 sleep 30 &
$ jobs -n
$

Job Specifications

jobs, fg, bg, kill, wait and disown accept a job specification (jobspec), which starts with %:

JobspecRefers to
%1, %2, ...job number 1, 2, ...
%+ or %%the current job
%-the previous job
%sleepthe job whose command starts with sleep
%?300the job whose command contains 300
$ jobs %1
[1]   Running                 sleep 100 &
$ jobs %?300
[3]+  Running                 sleep 300 &
$ jobs %+ %-
[3]+  Running                 sleep 300 &
[2]-  Running                 sleep 200 &
$ jobs %sleep
bash: jobs: sleep: ambiguous job spec
bash: jobs: %sleep: no such job
$ jobs %5
bash: jobs: %5: no such job

All three jobs start with sleep, so %sleep was ambiguous and Bash refused to guess. A prefix or substring jobspec must match exactly one job. Job numbers are the most reliable form.

Resuming in the Background with bg

bg sends SIGCONT to a stopped job, so it continues, and leaves it in the background:

$ bg
[3]+ sleep 300 &
$ jobs
[1]   Running                 sleep 100 &
[2]-  Running                 sleep 200 &
[3]+  Running                 sleep 300 &

Without an argument, bg acts on the current job (%+); bg %2 names a job explicitly. This is the standard way to rescue a command you started without &: press Ctrl + Z, then type bg. The program continues from exactly where it was paused, and the prompt is free again.

bg on a job that is already running in the background is refused:

$ sleep 50 &
[1] 569
$ bg %1
bash: bg: job 1 already in background

A job resumed with bg follows the background rules from lesson 135: if it tries to read from the terminal, it is stopped again, and its output appears in the middle of whatever you are doing.

Bringing a Job to the Foreground with fg

fg makes a job the foreground job again. If it is stopped, fg also sends SIGCONT. Bash prints the command, gives the job the terminal and waits for it, exactly as if you had just typed it:

$ fg %2
sleep 200
^C
$ jobs
[1]-  Running                 sleep 100 &
[3]+  Running                 sleep 300 &

Because job 2 was in the foreground, Ctrl + C reached it and ended it. A job running in the background cannot be interrupted with Ctrl + C, since the keyboard signals only go to the foreground; bringing it to the foreground first, or using kill %N (lesson 140), are the two ways to end it.

fg returns the exit status of the job, once it ends:

$ (sleep 0.5; exit 3) &
[1] 598
$ fg
( sleep 0.5; exit 3 )
$ echo "status $?"
status 3

When the job table is empty, there is nothing for fg or bg to act on:

$ fg
bash: fg: current: no such job
$ bg
bash: bg: current: no such job

A Practical Round Trip

Ctrl + Z and fg are often used to leave an interactive program briefly. Here cat collects lines into a file; it is stopped to check the file and then resumed:

$ cat > notes.txt
first line
^Z
[1]+  Stopped                 cat > notes.txt
$ wc -l notes.txt
1 notes.txt
$ fg
cat > notes.txt
second line
^D
$ cat notes.txt
first line
second line

The stopped cat kept its open file and its position. After fg, it continued reading from the keyboard until Ctrl + D ended its input. The same pattern works with editors, less, top and other full-screen programs.

Shortcuts: %N Alone and %N &

Typing a jobspec as a command is a shortcut: %2 alone means fg %2, and %2 & means bg %2:

$ sleep 60
^Z
[2]+  Stopped                 sleep 60
$ %2 &
[2]+ sleep 60 &
$ %1
sleep 50
^C

Notifications and set -b

By default Bash reports that a background job finished only when it is about to show the next prompt, so the message does not appear in the middle of your typing. With set -b (or set -o notify), Bash reports right away, even when the prompt is already shown:

$ set -b
$ sleep 1 &
[1] 571
$ true
$ [1]+  Done                    sleep 1

The Done line appeared after the prompt that was already printed, because the job ended while Bash was waiting for input. The cursor stays at the end of that line; pressing Enter shows a fresh prompt. set +b returns to the default.

Leaving a Shell That Has Jobs

As lesson 135 showed, exit warns once when stopped jobs exist. With shopt -s checkjobs, Bash also warns about running jobs and lists them:

$ shopt -s checkjobs
$ sleep 40 &
[1] 600
$ exit
exit
There are running jobs.
[1]+  Running                 sleep 40 &
$ jobs
[1]+  Running                 sleep 40 &
$ exit
exit

The second exit ended the shell. Bash treats jobs between the two exit commands as part of the check, so it did not warn again. The running sleep 40 was not killed by exit; it continued after the shell had ended, because Bash ends only stopped jobs on exit; running jobs receive SIGHUP when the terminal is closed (or on exit from a login shell with the huponexit option). To take a running job out of the table on purpose, so the shell neither tracks nor signals it, use disown:

$ sleep 30 &
[1] 572
$ disown %1
$ jobs
$

The process is still running; it is simply no longer one of this shell's jobs. disown -h %1 keeps the job in the table but makes sure Bash will not send it SIGHUP when the shell exits.

jobs, fg and bg in Scripts

Scripts run without job control. jobs still works, and so does kill %N, but fg and bg refuse to run:

sleep 0.5 &
sleep 0.6 &
jobs
jobs -p | wc -l
fg %1
echo "fg status $?"
bg %1; echo "bg status $?"
kill %2 && echo "kill %2 worked in a script"
wait
[1]-  Running                 sleep 0.5 &
[2]+  Running                 sleep 0.6 &
2
s1.sh: line 5: fg: no job control
fg status 1
s1.sh: line 7: bg: no job control
bg status 1
kill %2 worked in a script

A script has no reason to bring a job to the foreground; the wait built-in (lesson 138) does what a script needs, which is to pause until a job ends and collect its exit status. jobs -p is useful in scripts to get the PIDs of all jobs, for example to count how many are still running or to end them all in a cleanup trap with kill $(jobs -p).

set -m turns job control on in a script. Then fg is accepted, provided the script runs in a terminal:

set -m
sleep 0.3 &
jobs
fg %1
echo "fg status $?"
[1]+  Running                 sleep 0.3 &
sleep 0.3
fg status 0

This is rarely needed. With job control on, every background job also gets its own process group (lesson 135), which changes how it reacts to Ctrl + C and to terminal input, so turn it on in a script only when you specifically need that behavior.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Managing Jobs with jobs, fg, and bg and get answers drawn from it.

Signed-in readers only.