fg (Foreground)
The fg command is a shell builtin used to bring a background or suspended job into the foreground. Once in the foreground, the job regains control of the terminal, allowing you to interact with it or see its standard output directly.
Basic Syntax
fg [JOB_SPEC]
If JOB_SPEC is omitted, fg operates on the current job (the most recently backgrounded or suspended job).
Real-world Examples
1. Bringing the most recent job to the foreground
If you just pressed Ctrl+Z to suspend a text editor or a script, you can immediately bring it back.
# You are running a script
./update_database.sh
# You press Ctrl+Z to pause it and do something else
# [1]+ Stopped ./update_database.sh
# Bring it back
fg
2. Bringing a specific background job to the foreground
If you have multiple jobs running in the background, use the jobs command to find their job number, and then use fg.
jobs
# Output:
# [1] Running sleep 100 &
# [2]- Stopped nano config.txt
# [3]+ Running tail -f /var/log/syslog &
# Bring the nano editor back to the foreground
fg %2
3. Interacting with backgrounded scripts
Often, you might start a process in the background using &, realize it requires input (like a password prompt), and notice it gets suspended automatically waiting for that input (tty input).
# Start a script in the background
./deploy.sh &
# Notice it has stopped
jobs
# [1]+ Stopped (tty input) ./deploy.sh
# Bring it to the foreground to answer the prompt
fg %1