Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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:

kill $MY_PROCESS_ID

and my process id will be killed.

share|improve this question

2 Answers 2

up vote 4 down vote accepted
foo &
bg_pid=$!
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 %+

or

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
1  
As single % will refer to the last job started. –  Graeme Apr 3 at 13:10

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

foo &
my_process_id=$!

: other stuff ...

kill "$my_process_id"
share|improve this answer

Your Answer

 
discard

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.