0
0
Linux-cliHow-ToBeginner · 3 min read

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

In Linux, the fg command brings a background job to the foreground, allowing you to interact with it directly. The bg command resumes a stopped job in the background so it keeps running without blocking your terminal.
📐

Syntax

The fg and bg commands control jobs in your shell. 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, and then use bg and fg to manage it.

bash
sleep 100 &
# Starts sleep command in background
jobs
# Lists jobs with job numbers
kill -STOP %1
# Stops the job with job number 1
jobs
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]+ 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 without any jobs running or stopped.
  • Confusing process IDs (PIDs) with job numbers; fg and bg use job numbers, not PIDs.
bash
fg 1
# Wrong: missing % before job number
fg %1
# Correct usage
Output
bash: fg: 1: no such job # Then after correct usage, job resumes in foreground
📊

Quick Reference

CommandDescriptionExample
fg [%job_number]Bring a background or stopped job to the foregroundfg %1
bg [%job_number]Resume a stopped job in the backgroundbg %1
jobsList current jobs with their job numbersjobs
kill -STOP %job_numberStop (pause) a jobkill -STOP %1
kill -CONT %job_numberContinue a stopped jobkill -CONT %1

Key Takeaways

Use fg %job_number to bring a background 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.
fg and bg work with job numbers, not process IDs.