Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I start a process using foo &.

It outputs something like:

[1] 16915

This is the process id, I guess. How can I store this number into a variable named MY_PROCESS_ID (for example)?

Then I can do:


and my process id will be killed.

share|improve this question
up vote 4 down vote accepted
foo &
kill "$bg_pid"

You can also use the shell's internal kill command with (at least in case of bash) the job number:

foo &
kill %1

But that's probably not easier. May be easier interactively. But with

kill %+


kill %

you always get the last one. You can even identify the job to be killed by parts of the command line. See man bash; search for the block JOB CONTROL.

share|improve this answer
As single % will refer to the last job started. – Graeme Apr 3 '14 at 13:10

The $! variable is the PID if the last process started in the background. You would do:

foo &

: other stuff ...

kill "$my_process_id"
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.