如何通过 ssh pgrep,或将 pgrep 用作更大的 bash 命令?
How to pgrep over ssh, or use pgrep as a larger bash command?
我想 运行 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 作为一个更大系统的一部分,这就是额外疯狂的原因。
我仍然不明白您为什么需要 bash -c see 部分。你应该可以做到
ssh <host> pgrep -lf java || true
在本地机器上实际上 运行 true
,但你可以这样做
sssh <host> "pgrep -lf java || true"
如果您需要 true 才能在远程端。同样,假设您的 shell 接受该语法(即 bash)
您已经 运行在 bash shell 中设置了 ssh 另一端的所有内容,所以我认为您不需要显式调用 bash 再次——除非你的默认值 shell 是其他东西,那么你可能要考虑更改它或在适当的默认值 shell.
中编写脚本
我 运行 使用 python 的 os.system(command)
解决这个问题,它在子 shell.
中执行命令
pgrep
不匹配自身,但它确实匹配它的父级 shell,其中包括 pgrep 的参数。
我找到了解决方案:
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
我想 运行 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 作为一个更大系统的一部分,这就是额外疯狂的原因。
我仍然不明白您为什么需要 bash -c see 部分。你应该可以做到
ssh <host> pgrep -lf java || true
在本地机器上实际上 运行 true
,但你可以这样做
sssh <host> "pgrep -lf java || true"
如果您需要 true 才能在远程端。同样,假设您的 shell 接受该语法(即 bash)
您已经 运行在 bash shell 中设置了 ssh 另一端的所有内容,所以我认为您不需要显式调用 bash 再次——除非你的默认值 shell 是其他东西,那么你可能要考虑更改它或在适当的默认值 shell.
中编写脚本我 运行 使用 python 的 os.system(command)
解决这个问题,它在子 shell.
pgrep
不匹配自身,但它确实匹配它的父级 shell,其中包括 pgrep 的参数。
我找到了解决方案:
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