bg
Command: Running Jobs in the Background
Summary
The bg
command in Linux is used to move a suspended (stopped) job to the background, allowing you to continue using the terminal while the job runs. This is particularly useful for long-running processes that don't require constant user interaction.
Introduction
The bg
(background) command is a shell built-in that resumes a suspended job and runs it in the background. When a process is started in the foreground, it occupies the terminal, preventing you from executing other commands until the process finishes or is stopped. By using bg
, you can free up the terminal while the job continues to execute. You can then use the jobs
command to view the status of background jobs.
Use case and Examples
Resuming the Last Suspended Job
First, we start asleep
process in the background using &
. Then, we suspend it using Ctrl+Z
. Finally, bg
resumes the last suspended job (job ID 1) and moves it to the background. The &
symbol indicates that it's running in the background. 1234
is the process ID. Resuming a Specific Job
sleep 200 &
[1] 5678
sleep 300 &
[2] 9012
Ctrl+Z
Stopped
jobs
[1] Running sleep 200 &
[2]- Running sleep 300 &
[3]+ Stopped jobs
bg %3
[3] jobs &
sleep
processes are started in the background. Then jobs
command lists all current jobs. The Ctrl+Z
stop the jobs
command itself. The bg %3
command resumes the job with ID 3. Checking the Job Status
This shows how to check the status of a background job using thejobs
command. The output indicates that job 1 is currently running in the background. Commonly used flags
Flag | Description | Example |
---|---|---|
%job_id | Specifies the job ID to move to the background. If no job ID is specified, the most recently suspended job is used. | bg %2 (Resumes job ID 2) |
(Without arguments) | If no arguments are given, bg acts on the most recently stopped job. |