Background and Foreground
Your terminal can only show one thing at a time... or can it? Actually, you can run multiple processes and switch between them.
Foreground vs Background
- Foreground: Has control of your terminal, receives input
- Background: Running but not attached to terminal input
Starting in Background: &
Add & to run a command in the background:
The [1] 1234 means: job 1, PID 1234.
Suspending a Foreground Process: Ctrl+Z
A running process can be suspended (paused):
The process is now stopped - not running, but not dead.
jobs - List Background/Stopped Jobs
Job numbers in brackets, + marks the current job.
fg - Bring to Foreground
fg %1 brings job 1 to foreground.
bg - Resume in Background
If you suspended a process with Ctrl+Z:
bg resumes it in the background.
The Workflow
- Start a long process:
long_command - Oops, need terminal:
Ctrl+Z(suspend) - Resume in background:
bg - Check status:
jobs - Bring back:
fgwhen ready
Quick Background
If you forgot the &, don't start over:
- Ctrl+Z (suspend)
- bg (resume in background) Done.
Practical Example
Output from Background Jobs
Background jobs can still print output, which might be confusing. To suppress:
command > output.log 2>&1 &
Now output goes to file, not your terminal.
You're running a long process and realize you need the terminal. What's the fastest way to free it?
Quick Reference
| Command | Effect |
|---|---|
command & | Start in background |
Ctrl+Z | Suspend foreground process |
jobs | List background/stopped jobs |
fg | Bring job to foreground |
fg %N | Bring job N to foreground |
bg | Resume stopped job in background |
bg %N | Resume job N in background |
Key Takeaways
&starts commands in backgroundCtrl+Zsuspends the current foreground processbgresumes suspended process in backgroundfgbrings background process to foregroundjobsshows all background/stopped processes- Job numbers (
%1,%2) reference specific jobs
Next: killing misbehaving processes.