Bash脚本错误地计数了自己的实例

rob*_*o06 4 linux bash grep ps

我创建了一个bash脚本,该脚本计算了自身启动的实例。

在这里(在此示例中,我显示的是实例,而不是用进行计数wc -l):

#!/bin/bash
nb=`ps -aux | grep count_itself.sh`
echo "$nb"
sleep 20
Run Code Online (Sandbox Code Playgroud)

(当然,我的脚本名为count_itself.sh

执行它后,我希望它返回两行,但返回三行:

root@myserver:/# ./count_itself.sh
root    16225   0.0 0.0 12400   1176 pts/0  S+  11:46   0:00    /bin/bash ./count_itself.sh
root    16226   0.0 0.0 12408   564 pts/0   S+  11:46   0:00    /bin/bash ./count_itself.sh
root    16228   0.0 0.0 11740   932 pts/0   S+  11:46   0:00    grep count_itself.sh
Run Code Online (Sandbox Code Playgroud)

&标志(即在后台执行)并手动执行该ps -aux位时,它返回两个,这是我想要的:

root@myserver:/# ./count_itself.sh &
[1] 16233
root@myserver:/# ps -aux | grep count_itself.sh
root     16233  0.0  0.0  12408  1380 pts/0    S    11:48   0:00 /bin/bash ./count_itself.sh
root     16240  0.0  0.0  11740   944 pts/0    S+   11:48   0:00 grep --color=auto count_itself.sh
Run Code Online (Sandbox Code Playgroud)

我的问题是:为什么ps -aux脚本内的执行返回的行数比预期的多?

或者换句话说,为什么16226在我的第一个示例中创建了带有ID的进程?

编辑(因为大多数人似乎误解了我的问题):

我想知道为什么bash执行返回两个实例/bin/bash ./count_itself.sh,而不是为什么返回grep count_itself.sh

编辑2:

当然,我正在寻找一种避免这种行为并使脚本/bin/bash ./count_itself.sh仅返回一次的方法。

Tom*_*ech 5

这是grep输出的标准问题ps

一种解决方案是在字符周围添加一些方括号

nb=$(ps -aux | grep '[c]ount_itself.sh')
Run Code Online (Sandbox Code Playgroud)

这意味着您的grep实例本身不匹配,因为带有其参数的进程名称包含方括号,但其匹配的模式不匹配。

如注释中所述,您应在变量周围使用双引号,以保留空格。

您的结果中似乎有两个相同外壳程序实例的原因是,命令替换是在子外壳程序中执行的。有关仅显示父进程的详细信息,请参阅此问题