How to get process ID of background process?

Volodymyr Bezuglyy picture Volodymyr Bezuglyy · Dec 15, 2009 · Viewed 284.9k times · Source

I start a background process from my shell script, and I would like to kill this process when my script finishes.

How to get the PID of this process from my shell script? As far as I can see variable $! contains the PID of the current script, not the background process.

Answer

camh picture camh · Dec 16, 2009

You need to save the PID of the background process at the time you start it:

foo &
FOO_PID=$!
# do other stuff
kill $FOO_PID

You cannot use job control, since that is an interactive feature and tied to a controlling terminal. A script will not necessarily have a terminal attached at all so job control will not necessarily be available.