linux - 如何通过 ssh pgrep,或将 pgrep 用作更大的 bash 命令?

标签 linux bash ssh grep

我想运行 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/

相关文章:

linux - 作业 : Trying to calculate Easter using arithmetic evaluations

linux - 恢复用 rsync -avz --delete 删除的文件

bash - 如何使用 tomcat 7 在嵌入式 Web 应用程序中运行 bash 脚本(linux)?

mercurial - hg 存档到远程目录

bash - Bash-从循环中获取基本名称

python - 如何通过连接到 Linux 计算机的 GSM/GPRS 调制解调器发送彩信?

linux - 为什么 strace 不记录我所有的系统调用?

bash - 在 shell 中定义 "conditional"别名的最佳方法

bash - 使用 bash 我需要在文件名中的文件扩展名之前删除尾随空格

linux - 以 root 身份登录 EC2 实例