Sat 29 Dec 2007
Finding Child Process Pids in Bash Shell Scripts
Posted by admin under bash , linux , shell , software1 Comment
To control background child processes from a shell script you want to know the PID or job-id of the child. Here are some ways to do this:
First starting a background process echoes the job-id and pid of the process:
$ emacs &
[1] 15393The PID of the last command set to run in the background by the current shell or script is stored in $! variable:
$ echo $!
15393This you could find out by using the jobs command:
$ PID=`jobs -l | sed -n 's/^\[[0-9]*\] *+ *\([0-9]*\) .*$/\1/p'`; echo $PIDusing the fact that the last current (last started) job will be marked by a + in
jobs -l output.
To terminate the current job you don’t need the explicit job-id:
$ kill %+The exit status will be stored in the $? variable.
Read more in the Advanced Bash-Scripting Guide:Job Control Commands
January 12th, 2012 at 11:09 am
jobs -l also shows dead jobs