Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Linux bg Command

Linux bg Command

Linux Command Reference Linux Command Reference

bg is one of the core commands for job control in Linux/Unix systems, short for "background". Its main function is to move a currently suspended job to the background to continue running.

Basic concepts


Command syntax



bg [作业号]

Parameter Description

Parameters Description
No parameters Operates on the current job (i.e., the most recently suspended job)
Job number Specify the job number to operate on (you can use the jobs command to view it)

Use Cases

1. Resume a suspended job

When you use Ctrl+Z to suspend a foreground job, you can use the bg command to let it continue running in the background:

Example

$

sleep

100

 

Start a long-running command

^Z          

Press Ctrl+Z to suspend

[

1

]

sleep

100

$

bg

       

Let it continue running in the background

[

1

]

sleep

100

&

2. Resume by specifying the job number

When there are multiple suspended jobs, you can specify the job number:

Example

$

jobs

[

1

]

vim

file1.txt

[

2

]

$

bg

2

 

Let the second job continue running in the background

3. Use with the fg command

bg and fg(foreground) are a pair of complementary commands:


Practical Application Examples

Scenario: A typical development workflow

Example

1. Start the editor

$

vim

app.py

2. Need to temporarily run a test (press Ctrl+Z to suspend vim)

^Z

[

1

]

vim

app.py

3. Run the test script

$ python test.py

4. After the test, let the editor return to the background to continue working

$

bg

1

[

1

]

vim

app.py

&

5. View background jobs

$

jobs

[

1

]

vim

app.py

&


Frequently Asked Questions

Q1: How to view the current jobs?

Use jobs Command:

Example

$

jobs

[

1

]

sleep

100

&

[

2

]

vim

notes.txt

Q2: What is the difference between bg and &?

Q3: What happens to bg jobs after the terminal is closed?

By default, background jobs are terminated when the terminal is closed. To keep them, you can use:

Example

nohup

command

&

 

Or use tmux/screen


Advanced Tips

1. Use with disown

Detach a job from the terminal so it is not terminated even if the terminal is closed:

Example

$

sleep

1000

^Z

$

bg

$

disown

%

1

2. Use job number shortcuts

Example

$

bg

%

sleep

 

Resume jobs containing "sleep"


Summary flowchart

Mastering the bg The command can significantly improve your work efficiency under Linux, especially when you need to handle multiple tasks at the same time. Combined with jobs, fg and kill and other commands, you can achieve powerful job control capabilities.

Linux Command Reference Linux Command Reference