在 unix 中如何找出进程 运行 和 return true/false?

In unix how to find out if process running and return true/false?

我正在编写一个 unix shell 脚本,需要检查当前目录中是否有 运行 个进程 "xyz"。如果是,则继续执行下一个命令并显示 "Found It".

之类的文本

如果不是,请不要继续并显示像 "Process Not Found" 这样的文本。

我试过这样的事情:

if ps -ef | grep xyz
then
    echo "XYZ Process Found!"
else
    echo "XYZ Process Not Found!"
fi

但它只是向我显示进程并显示 "process found" 即使没有 xyz 进程。

我相信您想使用链接 bash-hackers wiki 中的 Command substition 根据值检查命令的输出 命令替换扩展为输出命令。这些命令在子 shell 中执行,它们的标准输出数据是替换语法扩展到的内容。 另外,计算行数并删除 grep。像,

if [[ $(ps -ef | grep xyz | grep -v grep | wc -l) != 0 ]]; then
        echo "XYZ Process Found!"
else
        echo "XYZ Process Not Found!"
fi

编辑

根据下面的评论,您可能应该使用

if [[ $(ps -ef | grep -c xyz)  -ne 1 ]]; then

这更容易阅读。

当您 运行 grep xyz 时,该过程 - grep xyz - 也是 运行ning 并且因此显示在 ps -ef 的输出中。
此 运行ning 进程命令行包含 xyz。因此 grep 将该行传递给输出。
因此,您总是获得零退出状态 - 即成功。

2 个解决方案:

  1. 使用if ps -ef | grep '[x]yz'; then。 (您可能想用 -q 抑制 grep 输出)
    运行 的 grep 命令是 grep [x]yz。这将打印在 ps -ef 输出中。
    显然,grep 过滤掉了这一行。 [x]yz 可以与 \[x\]yz 匹配,而不是 [x]yz

  2. 使用if pgrep -f xyz >/dev/null; then
    查看 man pgrep 了解更多详情..

您也可以使用pgrep。来自 pgrep(1):

pgrep looks through the currently running processes and lists the process IDs which match the selection criteria to stdout.

[...]

EXIT STATUS
0 One or more processes matched the criteria.
1 No processes matched.
2 Syntax error in the command line.
3 Fatal error: out of memory etc.

示例输出:

[~]% pgrep xterm
18231
19070
31727

您可以像这样在 if 语句中使用它:

if pgrep xterm > /dev/null; then
  echo Found xterm
else
  echo xterm not found
fi

注意:pgrep 不是标准实用程序(即它不在 POSIX 中),但至少在 Linux 上广泛可用,我相信大多数 BSD 系统。