0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use fg and bg Commands in Bash for Job Control

In bash, fg brings a background job to the foreground, letting you interact with it directly, while bg resumes a stopped job in the background so it keeps running without blocking your terminal. These commands help manage multiple tasks in one shell session.
📐

Syntax

The fg and bg commands control jobs in bash. You can specify which job to affect by its job number.

  • fg [%job_number]: Brings the specified job to the foreground. If no job number is given, it uses the most recent job.
  • bg [%job_number]: Resumes the specified stopped job in the background. If no job number is given, it uses the most recent stopped job.
bash
fg [%job_number]
bg [%job_number]
💻

Example

This example shows how to start a job, stop it, then resume it in the background and bring it back to the foreground.

bash
sleep 100 &
# Starts sleep in the background
jobs
# Lists jobs
kill -STOP %1
# Stops the job 1
jobs
# Shows stopped job
bg %1
# Resumes job 1 in background
jobs
fg %1
# Brings job 1 to foreground
Output
[1]+ Running sleep 100 & [1]+ Stopped sleep 100 [1]+ Running sleep 100 & sleep 100
⚠️

Common Pitfalls

Common mistakes include:

  • Not using % before the job number (e.g., fg 1 is wrong; use fg %1).
  • Trying to use fg or bg on jobs that do not exist or are already running in the foreground.
  • Confusing process IDs with job numbers; fg and bg use job numbers shown by jobs.
bash
fg 1
# Wrong: missing % before job number
fg %1
# Correct usage
Output
bash: fg: 1: no such job # then after correct command, job resumes in foreground
📊

Quick Reference

CommandDescriptionExample
fg [%job]Bring job to foregroundfg %2
bg [%job]Resume stopped job in backgroundbg %1
jobsList current jobs with numbersjobs
kill -STOP %jobStop a jobkill -STOP %1
kill -CONT %jobContinue a stopped jobkill -CONT %1

Key Takeaways

Use fg %job_number to bring a background or stopped job to the foreground.
Use bg %job_number to resume a stopped job in the background.
Always prefix job numbers with % when using fg or bg.
Use jobs to see current jobs and their numbers before using fg or bg.
Stopping a job with kill -STOP %job lets you control when to resume it.