为什么 "pgrep -f bash" 发出两个数字而不是一个?

Why does "pgrep -f bash" emit two numbers instead of one?

当我 运行 这个脚本在 shell:

printf "Current bash PID is `pgrep -f bash`\n"

使用此命令:

$ bash script.sh

我得到这个输出:

Current bash PID is 5430
24390

每次我运行它,我得到一个不同的数字:

Current bash PID is 5430
24415

第二行来自哪里?

当您使用反引号(或更现代的 $(...) 命令替换语法)时,您创建了一个子shell。这是一个 fork()ed-off,shell 进程的独立副本,它有自己的 PID,因此 pgrep 找到了 shell 的两个单独副本。 (此外,pgrep 可以在系统上找到与手头脚本完全无关的 bash 运行 的副本。


如果你想找到bash的当前副本的PID,你可以直接查找它(printfecho更好,因为内容可以包含反斜杠或者如果需要 echo -n 或非标准 bash 扩展 echo -e 的行为,但这些都不是这里的情况,所以 echo 没问题):

echo "Current bash PID is $$"

请注意,即使在子 shell 中执行,$$ 也会扩展为父 shell 的 PID。使用 bash 4.0 或更新版本,您可以使用 $BASHPID 查找当前 PID,即使在子 shell.

中也是如此

查看相关问题