Menu Close

How to easily understand Unix jobs management (ctrl+z, bg, jobs, fg)

techwetrust post image

When you are executing a long-running script in any Linux distribution, you can make it run in the background of your terminal.

In this tutorial, you’ll learn how to use bg, fg and Ctrl+Z to control Unix jobs and to send jobs from foreground to background and the other way around.

Terminal commands

Ctrl+Z – suspends the current foreground job
bg – runs a suspended job in the background
jobs – lists all running jobs
fg – brings back to foreground the most recent background job when it’s executed without any arguments

Examples step by step

As an example running job, I will run the following bash script that will print a message for 10 times with a pause of 2 seconds.

for i in {1..10}
   echo "Hello from - $i";
   sleep 2;


After we are executing the above script with bash , we can suspend it pressing the combination Ctrl + Z on our keyboard.

➜  bash 
Hello from - 1
Hello from - 2
[1]  + 8926 suspended  bash


Now, the script was suspended with Ctrl+Z and we can send it to run in the background writing bg.

➜  bg
[1]  + 9148 continued  bash
Hello from - 3                                           
➜  Hello from - 4
Hello from - 5
Hello from - 6

As you can see, the script will continue to print to the console by running in the background.

Another method to run a script in the background without suspending it is by appending an ampersand & to the command. Example bash &.


You can see the status of your jobs by using this command.

➜  jobs
[1]  + suspended  bash
➜  bg
[1]  + 9534 continued  bash
Hello from - 3                                           
➜  jobs
[1]  + running    bash


Now, we can bring back a job from running in the background to run in the foreground as a normally executed script. If we simply write fg it will bring back the most recent background job.

If we’ll have multiple jobs, we can use fg %id where id is from the bg listing.

➜  bash
Hello from - 1
Hello from - 2
Hello from - 3
[1]  + 10333 suspended  bash
➜  bg
[1]  + 10333 continued  bash
Hello from - 4                                           
➜  Hello from - 5
Hello from - 6
Hello from - 7

➜  fg
[1]  + 10333 running    bash
Hello from - 8
Hello from - 9
Hello from - 10

Spread the love

Leave a Reply