Adam Matan
Adam Matan

Reputation: 136141

Finding number of child processes

How do find the number of child processes of a bash script, from within the script itself?

Upvotes: 19

Views: 19844

Answers (6)

Jonny
Jonny

Reputation: 320

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[@]}

Upvotes: 5

nrc
nrc

Reputation: 231

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

Upvotes: 13

pretorh
pretorh

Reputation: 131

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)

Upvotes: 6

betabandido
betabandido

Reputation: 19704

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`

Upvotes: 15

chepner
chepner

Reputation: 530853

Use ps with the --ppid option to select children of the current bash process.

bash_pid=$$
child_count=$(ps -o pid= --ppid $bash_id | wc -l)
let child_count-=1    # If you don't want to count the subshell that computed the answer

(Note: this requires the Linux version of ps for --ppid. I don't know if there is an equivalent for BSD ps or not.)

Upvotes: 2

pdug
pdug

Reputation: 45

You may evaluate the shell builtin command jobs like:

counter = `jobs | wc -l`

Upvotes: -3

Related Questions