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 1is wrong; usefg %1). - Trying to use
fgorbgwithout any jobs running or stopped. - Confusing process IDs (PIDs) with job numbers;
fgandbguse 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
| Command | Description | Example |
|---|---|---|
| fg [%job_number] | Bring a background or stopped job to the foreground | fg %1 |
| bg [%job_number] | Resume a stopped job in the background | bg %1 |
| jobs | List current jobs with their job numbers | jobs |
| kill -STOP %job_number | Stop (pause) a job | kill -STOP %1 |
| kill -CONT %job_number | Continue a stopped job | kill -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.