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.

#!/bin/bash
for i in {1..10}
do
   echo "Hello from techwetrust.com - $i";
   sleep 2;
done

Ctrl+Z

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

➜  bash example.sh 
Hello from techwetrust.com - 1
Hello from techwetrust.com - 2
^Z
[1]  + 8926 suspended  bash example.sh

bg

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 example.sh
Hello from techwetrust.com - 3                                           
➜  Hello from techwetrust.com - 4
Hello from techwetrust.com - 5
Hello from techwetrust.com - 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 example.sh &.

jobs

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

➜  jobs
[1]  + suspended  bash example.sh
➜  bg
[1]  + 9534 continued  bash example.sh
Hello from techwetrust.com - 3                                           
➜  jobs
[1]  + running    bash example.sh

fg

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 example.sh
Hello from techwetrust.com - 1
Hello from techwetrust.com - 2
Hello from techwetrust.com - 3
^Z
[1]  + 10333 suspended  bash example.sh
➜  bg
[1]  + 10333 continued  bash example.sh
Hello from techwetrust.com - 4                                           
➜  Hello from techwetrust.com - 5
Hello from techwetrust.com - 6
Hello from techwetrust.com - 7

➜  fg
[1]  + 10333 running    bash example.sh
Hello from techwetrust.com - 8
Hello from techwetrust.com - 9
Hello from techwetrust.com - 10

Spread the love

Leave a Reply