Goal of the tutorial: The primary aim of this tutorial is to introduce you to the world of job management in shell scripts. By the end of this tutorial, you'll be able to run tasks in the background and manage multiple tasks simultaneously using shell scripts.
Learning outcomes: You will learn how to:
Utilize job control commands.
Prerequisites: Basic knowledge of shell scripting is required to understand the concepts explained in this tutorial. If you're new to shell scripting, you might want to take a look at an introductory shell scripting tutorial first.
What are jobs?
A job is an execution of a process in a shell. In simpler terms, whenever you run a command or script, it's called a job.
Background tasks: Jobs can be run in the background, meaning they run without interacting with your terminal. To run a job in the background, simply append the command with an ampersand (&).
bash
command &
Foreground tasks: Conversely, jobs that interact with your terminal are run in the foreground. Any command you run without an ampersand (&) is a foreground task.
Monitoring jobs: You can monitor your jobs with the jobs
command. This command lists all jobs with their status (running, stopped, etc.) and job number.
Controlling jobs: You can control jobs using commands like fg
, bg
, and kill
. fg
brings a job to the foreground, bg
sends a job to the background, and kill
terminates a job.
bash
sleep 10 &
This command will start a sleep job that will run for 10 seconds in the background. You'll immediately get the terminal's control back.
bash
jobs
This will give you a list of all jobs with their statuses and job numbers.
bash
fg %1
bg %1
kill %1
These commands will bring job number 1 to the foreground, send it to the background, and kill it, respectively.
In this tutorial, we covered the basics of job management in shell scripts. We learned what jobs are, how to run them in the background, and how to monitor and control them. To deepen your understanding, try to use these concepts regularly in your scripts.
Solutions:
sleep 30 &
jobs
jobs
, then kill it with kill %jobnumber
.Keep practicing these exercises until you feel comfortable with job management. Happy scripting!