This is a website by Willem van Zyl

I'm a project manager, software developer, Apple evangelist and geek from South Africa. I'm passionate about web and mobile application development, usability, productivity, physics, astronomy, science fiction and fantasy.

If you would like to contact me, message me on Twitter or send me an email.

How to manage background tasks in the Bash shell

10 Jun 2010

In the the Bash command line shell the "&" (ampersand) character is a control operator used to fork processes.

According to the man page for Bash:

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.

If the ampersand character is added to the end of a command, Bash will execute the command as a background process and assign a Job Number in addition to the usual Process ID (PID) to it:

Willem-Van-Zyls-MacBook-Pro:~ willem$ sleep 60 &
[1] 66984
Willem-Van-Zyls-MacBook-Pro:~ willem$ sleep 30 &
[2] 67001

In the above output, the "[1]" and "[2]" indicate the Job Numbers and the "66984" and "67001" indicate the PIDs.

To see a list of all running jobs, use the "jobs" command:

Willem-Van-Zyls-MacBook-Pro:~ willem$ jobs
[1]-  Running                 sleep 60 &
[2]+  Running                 sleep 30 &

To terminate a job, use the "kill" command and a "%" (percentage sign) with the Job Number appended:

kill %1
Do you like this? Share it:

Copyright © Geekology 2011. All Rights Reserved.

Hosted by Code. Like. Clockwork.