Start a Job and Return to the Shell : Run a Backgroud Job

Under some situation, we want to start some long jobs and then return to the shell to continue our work. We can do this by starting a job in the background. The shell such as bash will keep a list of background jobs and their status. But only one foreground job is allowed. Job control is one of the functions of all the modern shells. In this post, we are using bash.

Start a background job and return to the shell:

command &

The “&” symbol tells the shell to run this “command” in background. The use are return to the shell prompt immediately without waiting for the job to end. If the “&” symbol is not used, the user must wait for the command to end to get the shell prompt.

Another situation is that the user forget to start a long job with a “&” in the end and so the job is running in the foreground. The job can also be changed to the background by two steps:

First, suspend the foreground job:

Ctrl + Z

Second, continue the job in background:

bg

List the background jobs and their status:

The background jobs and their status can be queried by the build-in command jobs

jobs

The result is a list of lines. Each line starts with a number. This number can be used to control the jobs.

Bring a job to foreground and background:

Bring a suspended job to background has been introduced before, the format is:

bg %n

n is the number of the job that can be got from the job command.

Bring a background job the foreground:

fg %n

Kill a background job:

We can use the format “kill pid” to kill a process. But we can also use the job number to kill the background jobs like this:

kill %n

n is the job number.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *