'In bash find number of all descendants of a process

Suppose I have a dummy process with six descendants.

pstree -pc 101

dummy(101)──dummy(102)──dummy(103)──dummy(104)──dummy(105)──dummy(106)──sleep(107)

How do I get the number 6 for the above pid 101 in bash ?

Update: To Product above chain I use below bash script(dummy.sh) which is a recursive call to same script.

#!/bin/bash

if [[ "$#" -ne 1 ]]; then
    set -- 7
fi

if [[ "$1" -gt 2 ]]; then
    echo 'descendant process' "$1"
    "$0" "$(($1 - 1))"
else
    sleep 500
fi

Note: I want to get count of descendants of any process not just above example. The above is produced by bash terminal thus its pstree chain will look like pstree -pc 100. If I give input 100 script should return 7(as it has seven descendants)

bash(100)──dummy(101)──dummy(102)──dummy(103)──dummy(104)──dummy(105)──dummy(106)──sleep(107)


Solution 1:[1]

Try this (1192 is my systemd process, replace with the process number you want to check):

pstree -pc 1192 | grep -coP '\(\K[^\)]+'

The displayed total includes the parent process. Do -1 to get only the children.

This assumes pstree with a format output similar to this:

systemd(1)-+-ModemManager(814)-+-{ModemManager}(828)
           |                   `-{ModemManager}(831)
           |-NetworkManager(685)-+-{NetworkManager}(787)
           |                     `-{NetworkManager}(791)
           |-accounts-daemon(664)-+-{accounts-daemon}(682)
           |                      `-{accounts-daemon}(789)
           |-acpid(666)

Sadly pstree does not return a version number, so I cannot compare with your version.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1