首页 > 解决方案 > Does `pgrep` have a way to exclude child processes?

问题描述

I have a script called testscript.sh. I'm trying to use pgrep to count how many instances of the script are running:

pgrep -fc testscript.sh

I don't know how to exclude child processes and always end up with a count that includes them. For example, when I run a simple script I end up with a count of 2 instead of 1. Using pstree to check the PID, I get this:

sshd(4073)───bash(4074)───bash(21948)─┬─bash(21959)───sleep(22220)
                                      └─tail(21958)

PID 21948 is from me running ./testscript.sh. PID 21959 is from calling tail in the script. Is there a way to get pgrep to exclude everything to the right of the bash(21948) process?

标签: bashgrep

解决方案


  • 尽量不要使用-f,因为它会将整个命令行作为模式跟踪
  • 仅用于-x匹配确切的命令
  • 锚定您的-f使用^或以其他方式使用更具体的正则表达式模式
  • 但这需要-P 4074您提前知道父进程 ID。如果您知道获取父级的模式,则可以嵌套另一个 pgrep,即ps -c -P $(pgrep parent) script

推荐阅读