GICT knowledge base
How to Manage Background Jobs with bg and fg in Linux
Published
Managing background jobs is a fundamental skill for anyone working with the Linux terminal. Whether you are compiling code, running long downloads, monitoring systems, or simply multitasking, efficient job control can drastically improve your productivity and workflow. This in-depth guide explores the concepts, commands, and advanced techniques for managing background and foreground jobs using bg, fg, and related utilities in various Linux shells.
Introduction to Job Control in Linux Shells
Modern Linux shells (such as Bash, Zsh, and Ksh) provide powerful job control features that allow you to manage processes interactively. Job control enables you to:
- Run multiple commands simultaneously
- Move processes between the foreground and background
- Suspend, resume, or terminate jobs as needed
- Check the status of running, stopped, or completed jobs
Job control is especially useful for multitasking and for managing commands that take a long time to execute. Understanding how to control jobs is essential for anyone who frequently works with the command-line interface (CLI).
Foreground vs. Background Jobs
Foreground Jobs
A foreground job is a process that occupies your current shell session. While it’s running, your shell waits for it to finish before accepting further commands.
Example:
$ sleep 60
This command will make your terminal unresponsive until the sleep process ends or is interrupted.
Background Jobs
A background job runs without occupying the shell directly, allowing you to continue using the terminal for other tasks.
Example:
$ sleep 60 & [1] 12345
The ampersand (&) sends the process to the background. The shell prints a job number ([1]) and the process ID (12345).
Starting and Suspending Jobs
Starting a Job in the Background
Add & at the end of your command:
$ long_running_command &
Suspending a Foreground Job
You can suspend (pause) a running foreground job by pressing Ctrl+Z. This stops the job and returns control to the shell, allowing you to manage it further.
Example:
$ tail -f /var/log/syslog # Press Ctrl+Z [1]+ Stopped tail -f /var/log/syslog
Manipulating Jobs: bg and fg
What Are bg and fg?
bg (background): Resumes a suspended job in the background.
fg (foreground): Brings a background or stopped job to the foreground.
Using bg
After suspending a job (with Ctrl+Z), you can resume it in the background:
$ bg
If you have multiple jobs, specify the job number:
$ bg %2
Using fg
To bring a job to the foreground:
$ fg
Or specify the job number:
$ fg %1
Tip: Use jobs to see the job numbers.
Listing and Monitoring Jobs
Listing Jobs
The jobs command lists all jobs started in the current shell session:
$ jobs [1]+ Running sleep 60 & [2]- Stopped tail -f /var/log/syslog
Running: Currently executing in the background
Stopped: Suspended (via Ctrl+Z)
Checking Job Statuses
%n refers to job number n
+ and – indicate the default jobs for fg and bg
Signals and Job States
Common Signals
- SIGSTOP: (Ctrl+Z) Stops a process
- SIGCONT: (sent by bg/fg) Continues a stopped process
- SIGTERM: (default of kill) Asks a process to terminate gracefully
- SIGKILL: Forces a process to terminate immediately
Sending Signals
You can send signals using the kill command:
$ kill -SIGSTOP <pid> $ kill -SIGCONT <pid> $ kill -9 <pid> # SIGKILL
Disowning and Persisting Jobs
Why Disown a Job?
If you close your terminal or log out, background jobs receive a SIGHUP and may terminate. Disowning detaches a job from the shell, letting it run after logout.
Using disown
$ command & $ disown
Or disown a specific job:
$ disown %1
Using nohup for Persistence
nohup runs a command immune to hangups:
$ nohup long_running_command &
Output is redirected to nohup.out by default.
Using screen and tmux
For even more robust session persistence, use terminal multiplexers like screen or tmux:
Start a new session:
$ screen # or $ tmux
Run your command and detach (Ctrl+A D for screen, Ctrl+B D for tmux).
Reattach later with:
$ screen -r # or $ tmux attach
Practical Examples and Use Cases
Example 1: Suspending and Resuming a Job
Start a job in the foreground:
$ ping google.com
Press Ctrl+Z to suspend:
[1]+ Stopped ping google.com
Continue in the background:
$ bg [1]+ ping google.com &
Bring it back to foreground:
$ fg ping google.com
Example 2: Multiple Jobs
Run several commands in background:
$ sleep 100 & $ tail -f /var/log/syslog & $ jobs
Stop a job:
$ kill %1
Advanced Job Control Techniques
Job Control with Scripts
Job control is mostly an interactive shell feature. In scripts, use:
- & to run commands in background
- wait to pause until background jobs finish
#!/bin/bash sleep 10 & PID=$! echo "Sleeping in background, PID=$PID" wait $PID echo "Sleep finished"
Checking Background Job Exit Status
After background jobs finish, check their status:
$ wait %1 $ echo $?
Managing Jobs in Subshells
If you start a job in a subshell, you may lose control over it. Always manage jobs in the parent shell.
Chaining and Grouping Background Commands
Run a group of commands in the background:
$ { command1; command2; } &
Monitoring Output from Background Jobs
Redirect output to a file:
$ long_task > output.txt 2>&1 &
Or use tail -f output.txt to monitor progress.
Best Practices and Troubleshooting
- Use unique job names and descriptive commands to avoid confusion with multiple jobs.
- Monitor job status regularly using jobs and ps.
- Redirect output to files to avoid losing data when switching jobs.
- Disown or use nohup for background jobs that must survive logout.
- Avoid backgrounding critical system administration commands unless you’re sure they’re safe.
- Don’t forget about orphaned or zombie processes. Use ps aux | grep defunct to check.
- Document your background jobs in scripts or session notes for reproducibility.
Troubleshooting Common Issues
- Background job stopped after logout: Use nohup, disown, screen, or tmux.
- Job receives terminal input unintentionally: Only foreground jobs can read from the terminal. Use files or redirection for input.
- Lost track of jobs: Use jobs, ps, and top to find and manage them.
Conclusion
Mastering background and foreground job management with bg, fg, and related tools is essential for anyone working with Linux or Unix-like systems. These commands let you juggle multiple tasks, optimize your workflow, and maintain control over system resources. By understanding job states, signals, session persistence, and best practices, you can handle complex multitasking scenarios with confidence and efficiency.
Whether you are a developer, system administrator, researcher, or student, these job control skills will serve you well in both daily work and advanced automation. Explore further by experimenting with more advanced job management, integrating persistent multiplexers like screen and tmux, and automating workloads with scripts tailored to your needs.
[!NOTE] Always make sure you fully understand the implications of background processing and job control, especially in shared or production environments. Safe usage ensures reliable, predictable system behavior and the efficient use of server resources.
Related guides
How to Set Up zram on a Small VPS
Configure zram on Ubuntu with kernel and swap checks. Understand compressed memory limits, monitor real use and avoid unsafe swap-file changes.
LinuxHow to Find Services That Need a Restart After Updates with needrestart
Find services using outdated libraries with needrestart on Ubuntu. Read restart reports, review automatic restart policy and plan maintenance safely.
LinuxHow to Limit a Linux Service’s Memory with systemd
Limit a Linux service with systemd MemoryHigh, MemoryMax and swap controls. Check cgroup support, diagnose pressure and remove only your own policy.
LinuxHow to Protect SSH with CrowdSec on Ubuntu
Protect SSH with CrowdSec on Ubuntu. Connect log detection to firewall enforcement and test temporary blocking without losing administrator access.
