我想运行 pgrep 来查找某个进程的 ID。它工作得很好,除非作为更大的 bash 命令运行,因为 pgrep 还将匹配它的父 shell/bash 进程,其中包括匹配表达式作为其命令行的一部分。
pgrep 明智地从结果中排除了它自己的 PID,但不太明智,似乎没有排除其父进程的选项。
任何人都遇到过这个问题并有一个很好的解决方法。
更新。
pgrep -lf java || true
工作正常,但是
bash -c "(pgrep -lf java || true)"
echo 'bash -c "(pgrep -lf java || true)"' | ssh <host>
还识别父 bash 进程。
我正在将 pgrep 作为一个更大系统的一部分使用,这就是额外疯狂的原因。
最佳答案
我使用 python 的 os.system(command)
遇到了这个问题,它在子 shell 中执行命令。
pgrep
不匹配自身,但它匹配包含 pgrep 参数的父 shell。
我找到了一个解决方案:
pgrep -f the-arguments-here[^\[]
[^\[]
正则表达式确保它与 [
(正则表达式本身的开头)不匹配,因此排除了父 shell。
例子:
$ sh -c "pgrep -af the-arguments-here"
12345 actual-process with the-arguments-here
23456 sh -c pgrep -af the-arguments-here
对比:
$ sh -c "pgrep -af the-arguments-here[^\[]"
12345 actual-process with the-arguments-here
关于linux - 如何通过 ssh pgrep,或将 pgrep 用作更大的 bash 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29803901/