Job Control in Linux

May 22, 2005
This is a short tutorial on job control in Linux and Unix.

What are jobs ?

In Linux or Unix, a job is defined as a task or command that has started running but not yet finished what it is doing.

As Linux and Unix are multitasking operating systems, they allow you to run multiple commands simultaneously.

Each running command is called a job, and is assigned a unique id called the job number.

It is very easy to manage jobs in Linux.

The main commands you use for job control in Linux are as follows.

  • jobs - List all the jobs that are running or suspended.
  • fg - Bring the job to the foreground.
  • bg - Send the job to the background.
  • stop or Ctrl + z - Suspend the job.
  • kill or Ctrl + c - Terminate the job.

Unique identifiers for a job

You can point out a particular job using special identifiers. They are as follows.

%n - Job whose job number / job ID is the number n.

%word - Job whose command line starts with string word.

%?word - Job whose command line contains the string word.

%+ - Current job. You can also use %%.

%- - Previous job.

Managing jobs in Linux

How to manage jobs in Linux can be easily understood via an example.

Lets simultaneously run a few commands that takes some time to complete.

$ sleep 150 &
$ sleep 250 &
$ sleep 300 &
$ sleep 200 &

Here we have executed 4 sleep commands and all are started in the background as denoted by &.

List the running jobs

$ jobs

And the output is ...

[1]    running    sleep 150
[2]    running    sleep 250
[3]  - running    sleep 300
[4]  + running    sleep 200

In the output above, the number within [ and ] is the job number (job ID). The job number is unique for each job.

Bring a job to the foreground

$ fg %job-number

To bring job number 2 to the foreground, you run the following command.

$ fg %2

Suspend the job

To suspend a job, you first bring the job to the foreground and then press the keys Ctrl + z.

Alternately, you can also suspend a job running in the background as follows.

$ stop %job-number

Send a job to the background

$ bg %job-number

To resume the suspended job 2 in the background, you can run the following command.

$ bg %2

List only running jobs

$ jobs -r

List only suspended jobs

$ jobs -s

List process IDs of the jobs

This command will list process IDs of the jobs in addition to the normal information.

$ jobs -l

Terminate a job

To terminate a job, you first bring the running job to the foreground, and then press the keys Ctrl + c.

You can also terminate a job without bringing it in the foreground just by passing the job number to kill.

$ kill %job-number

For example, to kill the 3rd job, you can do as follows.

$ kill %3