How do find the number of child processes of a bash script, from within the script itself?
To obtain the PID of the bash script you can use variable $$
.
Then, to obtain its children, you can run:
bash_pid=$$
children=`ps -eo ppid | grep -w $bash_pid`
ps
will return the list of parent PIDs. Then grep
filters all the processes not related to the bash script's children. In order to get the number of children you can do:
num_children=`echo $children | wc -w`
Actually the number you will get will be off by 1, since ps
will be a child of the bash script too. If you do not want to count the execution of ps
as a child, then you can just fix that with:
let num_children=num_children-1
UPDATE: In order to avoid calling grep
, the following syntax might be used (if supported by the installed version of ps
):
num_children=`ps --no-headers -o pid --ppid=$$ | wc -w`