🔄 Commands: bg and fg (Job Control)
In Linux, "Job Control" allows you to manage multiple processes within a single terminal session. The bg (background) and fg (foreground) commands are used to move these processes between states.
1. The Core Concept: Foregrounds vs. Backgrounds
- Foreground: The process currently "owning" your terminal. You can’t type other commands until it finishes.
- Background: The process is running in the "back," allowing you to keep using the terminal prompt for other tasks.
2. The Workflow (The "Suspend" Trick)
To use bg and fg effectively, you first need to know how to pause a running process.
- Start a task: Suppose you are compiling your Java code or a large LaTeX document.
- Suspend it: Press
Ctrl + Z. This stops the process and gives you back the prompt. - View jobs: Type
jobsto see your suspended tasks. Each gets a number (e.g.,[1]).
3. Usage Examples
A. Moving to Background (bg)
If you started a long-running simulation for your Quantum Computing research and realized you forgot to add the & at the end to make it a background task:
- Press
Ctrl + Z(suspends the task). - Type
bg. - The task now continues running, but you have your terminal back!
B. Bringing to Foreground (fg)
If you want to interact with a background task again (like a text editor or a process you want to stop with Ctrl + C):
- Type
jobsto find the ID. - Type
fg %1(to bring job #1 back to the front).
4. Comparison Table
| Command | Action | Result |
|---|---|---|
& |
Add to end of command | Starts the command in the background immediately. |
Ctrl + Z |
Keyboard Shortcut | Pauses/Suspends the current foreground task. |
bg |
Move to background | Resumes a suspended task in the background. |
fg |
Move to foreground | Resumes a suspended task in the foreground. |
jobs |
Status check | Lists all active and suspended tasks in the current shell. |
5. Practical Scenarios for Your Setup
- Android/Java Dev: If you launch a local server or a specialized debugger from the terminal, move it to the background so you can continue using
gitorlsin the same window. - Arch Linux Customization: When testing a script for Hyprland or Waybar, run it with
&or move it tobg. This lets you see the logs in the terminal while you keep working. - Tutorial Writing: If you are using a CLI-based tool to convert your e-book drafts, you can keep the converter in the background and only bring it to the foreground when you need to check for specific error messages.
6. Pro-Tips
- The
%sign: Whilefgworks on the most recent job,fg %2targets a specific job ID found in thejobslist. - Disown: If you want to close your terminal but keep a background job running, use the command
disown. This prevents the process from being killed when the shell closes. - Arch Context: If you're running a heavy update or a AUR compilation that is taking too long,
Ctrl + Zandbgcan let you check yourpacmanlogs or browse files while the compilation continues.