bg (Background)
The bg command is a shell builtin used to resume suspended jobs and run them in the background. This allows you to continue using your terminal while the process executes asynchronously.
Basic Syntax
bg [JOB_SPEC]
If JOB_SPEC is omitted, bg operates on the current job (usually the last one you suspended).
How to Suspend a Job
To use bg, you first need a suspended job. While a command is running in the foreground, you can suspend it by pressing Ctrl+Z.
Real-world Examples
1. Moving a running process to the background
Imagine you start a large tar archive process and realize it will take 10 minutes, but you need your terminal back.
# 1. Start the command
tar -czvf backup.tar.gz /var/log/
# 2. Press Ctrl+Z to suspend it
# Output: [1]+ Stopped tar -czvf backup.tar.gz /var/log/
# 3. Resume it in the background
bg
# Output: [1]+ tar -czvf backup.tar.gz /var/log/ &
2. Starting a process directly in the background
While not using the bg command itself, the most common way to put a process in the background is appending an ampersand (&) to the command when launching it.
./long_script.sh &
3. Resuming a specific job
If you have multiple suspended jobs (viewed using the jobs command), you can specify which one to put in the background.
jobs
# [1] Stopped nano file1
# [2]- Stopped nano file2
# [3]+ Stopped find / -name "*.log"
# Resume job 3 in the background
bg %3
Note: You usually wouldn't background an interactive program like nano or vim, as they require terminal input. Backgrounding them will keep them suspended waiting for input. bg is best used for non-interactive tasks like compiling code, moving files, or running scripts.