bash - 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?
解决方案
- 尽量不要使用
-f
,因为它会将整个命令行作为模式跟踪 - 仅用于
-x
匹配确切的命令 - 锚定您的
-f
使用^
或以其他方式使用更具体的正则表达式模式 - 但这需要
-P 4074
您提前知道父进程 ID。如果您知道获取父级的模式,则可以嵌套另一个 pgrep,即ps -c -P $(pgrep parent) script
推荐阅读
- python-3.x - 如何在 Windows 7 中自动安装 python 库(在我们的脚本文件中导入)
- dialogflow-es - 保存意图时出现许多弹出错误
- php - 如何获取响应php cURL的“内容长度”
- javascript - ExtJS:如何在函数中更改组件“labelStyle”?
- java - 使用 Apache Tika 将 Docx 文件转换为 Java 中的 Html 时,内容背景和颜色不保留
- python - python中没有睡眠功能的多线程控制
- javascript - asp.net mvc中的多个Ajax加载问题
- python - 如何在文件名中查找文本片段?
- javascript - javascript中的数据库
- css - Letterspacing 不适用于特定的双字母