UNIX Tip of the Week

Job Control


To run a job in the background (detached), an ampersand is appended to the jobname:

$ calculate_pi &
[1]     26559
$
The [1] tells us that it's our first background job for this session, hereafter to be referred to as %1.
The 26559 tells us the PID (process ID number).
For the duration of your session, these two numbers are related, i.e. %1 means the same thing as 26559.

One may launch a number of background jobs:

$ sleep 30 &
[1]     26564
$ sleep 20 &
[2]     26568
$ sleep 10 &
[3]     26573
$             
$ jobs
[3]    Running                 sleep 10 &
[2]    Running                 sleep 20 &
[1]    Running                 sleep 30 &

Moving your jobs between the foreground and the background

fg moves a backgrounded job to the foreground
^Z suspends a foreground task (giving you the prompt so that you can move it to the background)
bg moves a suspended job into the background

fg accepts the "percent" specifiers as arguments. For example, fg %3 runs %3 as an attached process.

$ bigjob
                                           <-- Here I hit ^Z
[1] + Stopped                  bigjob
oz:tips: bg
[1]     bigjob&
oz:tips:                                   I got the prompt back - it's running in the background  
oz:tips: fg                                I once again tell it to run in the foreground
bigjob                                     And once it is, I again hit ^Z to suspend it...
[1] + Stopped                  bigjob
oz:tips: bg                                ...and finally move it again to the background
[1]     bigjob&

Revised: March 20, 2000