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
Terminal
$# This runs in foreground (blocks terminal)
$sleep 30
(terminal is blocked for 30 seconds)

Starting in Background: &

Add & to run a command in the background:

Terminal
$sleep 30 &
[1] 1234
$# Terminal is immediately available
$echo 'I can do other things'
I can do other things

The [1] 1234 means: job 1, PID 1234.

Suspending a Foreground Process: Ctrl+Z

A running process can be suspended (paused):

Terminal
$sleep 100
$# (press Ctrl+Z)
^Z [1]+ Stopped sleep 100

The process is now stopped - not running, but not dead.

jobs - List Background/Stopped Jobs

Terminal
$sleep 100 &
[1] 1234
$sleep 200 &
[2] 1235
$jobs
[1]- Running sleep 100 & [2]+ Running sleep 200 &

Job numbers in brackets, + marks the current job.

fg - Bring to Foreground

Terminal
$jobs
[1]- Running sleep 100 & [2]+ Running sleep 200 &
$fg %1
sleep 100 (now attached to terminal)

fg %1 brings job 1 to foreground.

bg - Resume in Background

If you suspended a process with Ctrl+Z:

Terminal
$# Process was Ctrl+Z stopped
$bg %1
[1]+ sleep 100 &

bg resumes it in the background.

The Workflow

  1. Start a long process: long_command
  2. Oops, need terminal: Ctrl+Z (suspend)
  3. Resume in background: bg
  4. Check status: jobs
  5. Bring back: fg when ready

Quick Background

If you forgot the &, don't start over:

  1. Ctrl+Z (suspend)
  2. bg (resume in background) Done.

Practical Example

Terminal
$# Start a download
$wget https://example.com/large-file.zip &
[1] 1234
$
$# Start another
$npm install &
[2] 1235
$
$# Check both
$jobs
[1]- Running wget ... [2]+ Running npm install &

Output from Background Jobs

Background jobs can still print output, which might be confusing. To suppress:

hljs bash
command > output.log 2>&1 &

Now output goes to file, not your terminal.

Knowledge Check

You're running a long process and realize you need the terminal. What's the fastest way to free it?

Quick Reference

CommandEffect
command &Start in background
Ctrl+ZSuspend foreground process
jobsList background/stopped jobs
fgBring job to foreground
fg %NBring job N to foreground
bgResume stopped job in background
bg %NResume job N in background

Key Takeaways

  • & starts commands in background
  • Ctrl+Z suspends the current foreground process
  • bg resumes suspended process in background
  • fg brings background process to foreground
  • jobs shows all background/stopped processes
  • Job numbers (%1, %2) reference specific jobs

Next: killing misbehaving processes.