We've all been there - you run what you think will be a quick command like tar -czvf archive.tar.gz large_directory/
, only to realize it's taking much longer than expected. The terminal is blocked, and you need to continue working. Here's how to properly background processes.
The standard workflow involves these steps:
# Start a process (example)
$ python3 long_script.py
# Suspend it with Ctrl+Z
^Z
[1]+ Stopped python3 long_script.py
# Send to background
$ bg
# Verify it's running
$ jobs
[1]+ Running python3 long_script.py &
For more control, consider these approaches:
# Start process directly in background
$ python3 script.py &
# Disown a process to prevent SIGHUP
$ nohup python3 script.py &
When you need to bring a background process back:
# List background jobs
$ jobs
[1]- Running python3 script1.py &
[2]+ Stopped python3 script2.py
# Bring to foreground
$ fg %2
Common use cases:
# Archiving directories
$ tar -czf backup.tar.gz /data/ &
# Database operations
$ mysqldump -u user -p database > backup.sql &
# Long compilations
$ make -j4 all &
Remember that background processes:
- Still output to the terminal by default (use redirection)
- Will be terminated if you close the terminal (use
nohup
orscreen
) - Might be affected by shell job control settings
When you accidentally start a long-running process in the foreground, the standard way to background it is:
# Start a process (example)
$ tar -czf archive.tar.gz large_directory/
^Z # Press Ctrl+Z to suspend
[1]+ Stopped tar -czf archive.tar.gz large_directory/
$ bg # Resume in background
[1]+ tar -czf archive.tar.gz large_directory/ &
For processes you know will take time, append &:
$ tar -czf archive.tar.gz large_directory/ &
[1] 12345 # PID shown immediately
$ jobs # List background jobs
[1]- Running tar -czf archive.tar.gz large_directory/ &
[2]+ Stopped ping example.com
$ fg %1 # Bring job 1 to foreground
$ kill %2 # Terminate job 2
Compiling large projects is a common use case:
$ make all
^Z
$ bg
$ disown -h %1 # Prevent termination if logout
$ nohup ./long_script.sh > output.log 2>&1 &
$ ps -o pid,stat,cmd
PID STAT CMD
12345 S tar -czf archive.tar.gz large_directory/