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.
You need to save the PID of the background process at the time you start it:
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.
pgrep
can get you all of the child PIDs of a parent process. As mentioned earlier$$
is the current scripts PID. So, if you want a script that cleans up after itself, this should do the trick:$$
is the current script's pid$!
is the pid of the last background processHere's a sample transcript from a bash session (
%1
refers to the ordinal number of background process as seen fromjobs
):An even simpler way to kill all child process of a bash script:
The
-P
flag works the same way withpkill
andpgrep
- it gets child processes, only withpkill
the child processes get killed and withpgrep
child PIDs are printed to stdout.You might also be able to use pstree:
This typically gives a text representation of all the processes for the "user" and the -p option gives the process-id. It does not depend, as far as I understand, on having the processes be owned by the current shell. It also shows forks.
You can use the
jobs -l
command to get to a particular jobLIn this case, 46841 is the PID.
From
help jobs
:jobs -p
is another option which shows just the PIDs.