Job Management

Tutorial 2 of 4

1. Introduction

  • 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:

  • Understand what jobs are in a shell script.
  • Run tasks in the background.
  • Monitor and control jobs.
  • 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.

2. Step-by-Step Guide

  • 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.

3. Code Examples

  • Running a job in the background: Here's a simple example of how to run a job in the background:

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.

  • Monitoring jobs: Here's how you can monitor your jobs:

bash jobs
This will give you a list of all jobs with their statuses and job numbers.

  • Controlling jobs: Here's how to control jobs:

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.

4. Summary

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.

5. Practice Exercises

  1. Exercise 1: Run a sleep command for 30 seconds in the background.
  2. Exercise 2: List all running jobs.
  3. Exercise 3: Kill the sleep job you started in exercise 1.

Solutions:

  1. sleep 30 &
  2. jobs
  3. First, find the job number with jobs, then kill it with kill %jobnumber.

Keep practicing these exercises until you feel comfortable with job management. Happy scripting!