Bash - 一个脚本两个进程

Bash - Two processes for one script

我有一个 shell 脚本,名为 test.sh :

#!/bin/bash
echo "start"
ps xc | grep test.sh | grep -v grep | wc -l
vartest=`ps xc | grep test.sh | grep -v grep | wc -l `
echo $vartest
echo "end"

输出结果为:

start
1
2
end

所以我的问题是,为什么有两个 test.sh 进程 运行 当我使用 `` 调用 ps 时(同样发生在 $() 中)而不是当我调用ps直接? 我怎样才能得到想要的结果(1)?

当您启动一个子 shell 时,与反引号一样,bash 会分叉自身,然后执行您想要 运行 的命令。然后你还 运行 一个管道,它导致所有这些都在它们自己的子 shell 中 运行,所以你最终得到等待管道完成的脚本的 "extra" 副本它可以收集输出并 return 到原始脚本。

我们将做一些实验,使用 (...) 到 运行 在子 shell 中显式处理,并使用 pgrep 命令为我们做 ps | grep "name" | grep -v grep,只是向我们展示匹配我们的字符串的进程:

echo "Start"
(pgrep test.sh)
(pgrep test.sh) | wc -l
(pgrep test.sh | wc -l)
echo "end"

对我来说 运行 产生输出:

Start
30885
1
2
end

所以我们可以看到,子 shell 中的 运行ning pgrep test.sh 仅找到 test.sh 的单个实例,即使该子 shell 本身是管道的一部分。但是,如果子 shell 包含管道,那么我们会得到等待管道完成的脚本的分叉副本