SyntaxStudy
Sign Up
Linux / Bash Background Jobs: jobs, bg, fg, and nohup
Linux / Bash Beginner 1 min read

Background Jobs: jobs, bg, fg, and nohup

Bash provides a simple job control system for managing multiple processes within a single terminal session. When you append `&` to a command it runs in the background, immediately returning the shell prompt. The shell assigns it a job number. You can then start more commands while the background job runs concurrently. The `jobs` command lists all active jobs in the current shell session, showing their job numbers, status (running or stopped), and commands. `fg %n` brings job number n to the foreground. `bg %n` resumes a stopped job in the background. You can suspend any foreground process with Ctrl+Z, then decide whether to resume it in the foreground or background. When you close a terminal or log out, background jobs receive a SIGHUP signal and typically terminate. The `nohup` command prevents this by redirecting SIGHUP. Combined with `&`, it allows processes to outlive the terminal session. For production use, `screen`, `tmux`, or `systemd` services are preferred over `nohup` because they offer session management and restart policies.
Example
# Run a command in the background
long_running_script.sh &
# [1] 4567  — job number 1, PID 4567

# Start multiple background jobs
sleep 100 &
sleep 200 &
sleep 300 &

# List all jobs in the current session
jobs
# [1]   Running    sleep 100 &
# [2]-  Running    sleep 200 &
# [3]+  Running    sleep 300 &
# '+' = current job, '-' = previous job

# Bring job 2 to the foreground
fg %2

# Suspend the foreground process
# Press: Ctrl+Z
# [2]+  Stopped    sleep 200

# Resume suspended job in the background
bg %2

# Resume in the foreground
fg %2

# Kill a background job
kill %1
kill %3

# Wait for all background jobs to finish
wait

# ---- nohup: survive terminal close ----
nohup ./server.sh &                       # Output → nohup.out
nohup ./server.sh > /var/log/server.log 2>&1 &

# ---- disown: detach a running job ----
./server.sh &
disown %1       # Remove from job table (survives terminal close)

# ---- screen / tmux (brief reference) ----
# screen -S mysession      start named session
# Ctrl+A, D               detach
# screen -r mysession      reattach

# tmux new -s deploy       start named session
# Ctrl+B, D               detach
# tmux attach -t deploy    reattach