You have probably noticed that when you enter a command from a Terminal, you normally have to wait for the command to finish before the shell returns control to you. This means that you have sent the command in the foreground. However, there are occasions when this is not desirable.
Suppose, for example, that you decide to copy a large directory recursively to another. You have also decided to ignore errors, so you redirect the error channel to /dev/null:
cp -R images/ /shared/ 2>/dev/null |
Such a command can take several minutes until it is fully executed. You then have two solutions: the first one is violent, and means stopping (killing) the command and then doing it again when you have the time. To do this, type Ctrl+c: this will terminate the process and take you back to the prompt. But wait, don't do it yet! Read on.
Suppose you want the command to run while you do something else. The solution is then to put the process into the background. To do this, type Ctrl+z to suspend the process:
$ cp -R images/ /shared/ 2>/dev/null # Type C-z here [1]+ Stopped cp -R images/ /shared/ 2>/dev/null $ |
and there you are again at the prompt. The process is then on standby, waiting for you to restart it (as shown by the Stopped keyword). That, of course, is what you want to do, but in the background. Type bg (for BackGround) to get the desired result:
$ bg [1]+ cp -R images/ /shared/ 2>/dev/null & $ |
The process will then start running again as a background task, as indicated by the & (ampersand) sign at the end of the line. You will then be back at the prompt and able to continue working. A process which runs as a background task, or in the background, is called a background job.
Of course, you can start processes directly as background tasks by adding an & character at the end of the command. For example, you can start the command to copy the directory in the background by writing:
cp -R images/ /shared/ 2>/dev/null & |
If you want, you can also restore this process to the foreground and wait for it to finish by typing fg (ForeGround). To put it into the background again, type the sequence Ctrl+z, bg.
You can start several jobs this way: each command will then be given a job number. The shell command jobs lists all the jobs associated with the current shell. The job preceded by a + sign indicates the last process begun as a background task. To restore a particular job to the foreground, you can then type fg <n> where <n> is the job number, i.e. fg 5.
Note that you can also suspend or start full-screen applications this way, such as less or a text editor like Vi, and restore them to the foreground when you want.