Jobs: bg, fg & nohup
Run commands in the background, bring them forward, and keep them alive after logout.
Syntax
command &
jobs
fg %1
nohup command &A long-running command normally ties up your terminal. Job control lets you push it into the background and get your prompt back.
Background and foreground
- End a command with
&to start it in the background. - Press Ctrl+Z to pause the current command.
bgresumes the paused job in the background;fgbrings it back to the foreground.jobslists the background jobs of this shell.
Surviving logout
Background jobs still stop when you close the terminal. Wrap a command in nohup ... & so it keeps running after you log out.
Example
# Start a long job in the background
./backup.sh &
# [1] 2043
# See background jobs
jobs
# [1]+ Running ./backup.sh &
# Bring job 1 back to the foreground
fg %1
# Keep running after you log out
nohup ./server.sh &When to use it
- A developer runs a long build with 'make &' to background it, then continues editing source files in the same terminal.
- A sysadmin uses 'Ctrl+Z' then 'bg' to background a running 'vim' session, run a quick check, then 'fg' to return to editing.
- A DevOps engineer uses 'nohup ./deploy.sh &' to keep a deployment running after closing their SSH session.
More examples
Background and list jobs
Shows how & runs a command in the background and jobs lists all current shell background jobs with their IDs.
# Start a command in the background with &
sleep 60 &
# [1] 7890
# List all background jobs
jobs
# [1]+ Running sleep 60 &Suspend, background, and foreground
Demonstrates the full Ctrl+Z / bg / fg cycle for moving a process between foreground and background.
# Start a process
vim file.txt
# Press Ctrl+Z to suspend it
# [1]+ Stopped vim file.txt
# Resume it in the background
bg %1
# Bring it back to the foreground
fg %1Survive session close with nohup
Uses nohup to make a background job immune to SIGHUP so it persists after the SSH session ends.
# Run job immune to hangup signal
nohup ./long_backup.sh > backup.log 2>&1 &
# [1] 8001
# Job keeps running after SSH disconnect
# Check output later
tail -f backup.log
Discussion