Finding number of child processes

You can also use pgrep:

child_count=$(($(pgrep --parent $$ | wc -l) - 1))

Use pgrep --parent $$ to get a list of the children of the bash process.
Then use wc -l on the output to get the number of lines: $(pgrep --parent $$ | wc -l) Then subtract 1 (wc -l reports 1 even when pgrep --parent $$ is empty)


If job count (instead of pid count) is enough I just came with a bash-only version:

job_list=($(jobs -p))
job_count=${#job_list[@]}

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`

I prefer:

num_children=$(pgrep -c -P$$)

It spawns just one process, you do not have to count words or adjust the numbers of PIDs by the programs in the pipe.

Example:

~ $ echo $(pgrep -c -P$$)
0
~ $ sleep 20 &
[1] 26114
~ $ echo $(pgrep -c -P$$)
1

Tags:

Bash

Process

Pid