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 1is wrong; usefg %1). - Trying to use
fgorbgon jobs that do not exist or are already running in the foreground. - Confusing process IDs with job numbers;
fgandbguse job numbers shown byjobs.
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
| Command | Description | Example |
|---|---|---|
| fg [%job] | Bring job to foreground | fg %2 |
| bg [%job] | Resume stopped job in background | bg %1 |
| jobs | List current jobs with numbers | jobs |
| kill -STOP %job | Stop a job | kill -STOP %1 |
| kill -CONT %job | Continue a stopped job | kill -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.