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)
CodePudding user response:
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.
CodePudding user response:
I think you're looking for something like this:
pstree -pcA 101 | awk 'BEGIN { RS="---"; FS="[()]" } FNR==1 { var=$1; n; next } $1==var { n } END { print n }'
[EDIT]
Works for different parent's name.
pstree -pcA 29076 | awk 'BEGIN { RS="---"; FS="[()]"; n } FNR==2 { var=$1; n } FNR>2 && $1==var { n } END { print n }'