0
0
Linux CLIscripting~5 mins

fg and bg commands in Linux CLI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Sometimes you start a task in the terminal and want to pause it or run it in the background so you can do other things. The fg and bg commands help you switch tasks between the foreground and background easily.
When you start a long-running script and want to pause it temporarily to do something else.
When you accidentally start a process in the foreground but want it to keep running while you use the terminal.
When you want to bring a background task back to the foreground to interact with it.
When managing multiple tasks in one terminal session without opening new windows.
When you want to stop a running process without killing it and resume it later.
Commands
Starts a simple command that waits for 100 seconds. This runs in the foreground and blocks the terminal.
Terminal
sleep 100
Expected OutputExpected
No output (command runs silently)
Pressing Ctrl+Z pauses (suspends) the running foreground process and puts it in the background in a stopped state.
Terminal
Ctrl+Z
Expected OutputExpected
[1]+ Stopped sleep 100
Resumes the stopped job in the background so it keeps running but frees the terminal for other commands.
Terminal
bg
Expected OutputExpected
[1]+ sleep 100 &
Lists all current jobs with their status so you can see which tasks are running or stopped in the background.
Terminal
jobs
Expected OutputExpected
[1]+ Running sleep 100 &
Brings the most recent background job back to the foreground so you can interact with it directly.
Terminal
fg
Expected OutputExpected
sleep 100
Key Concept

If you remember nothing else, remember: fg brings a background job to the foreground, and bg resumes a stopped job in the background.

Common Mistakes
Trying to use fg or bg without any jobs running
The commands fail because there is no job to bring to foreground or background.
Make sure you have a stopped or background job by running jobs before using fg or bg.
Using bg on a job that is already running
bg will not change the state and may confuse the user since the job is already in background running.
Check job status with jobs and only use bg on stopped jobs.
Pressing Ctrl+C to stop a job instead of Ctrl+Z
Ctrl+C kills the process instead of pausing it, so you lose the job.
Use Ctrl+Z to pause and suspend the job if you want to resume it later.
Summary
Use Ctrl+Z to pause a running foreground job and send it to background in stopped state.
Use bg to resume a stopped job in the background so it keeps running.
Use fg to bring a background job back to the foreground for interaction.