use*_*469 3 unix bash shell ps
我有一个名为test.sh的shell脚本:
#!/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"
Run Code Online (Sandbox Code Playgroud)
输出结果是:
start
1
2
end
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,为什么有两个test.sh进程在我使用``调用ps时运行(与$()相同)而不是直接调用ps时?我怎样才能得到理想的结果(1)?
当您启动子shell时,与反引号一样,bash自行分叉,然后执行您想要运行的命令.然后你还运行一个管道,导致所有这些都在他们自己的子shell中运行,所以你最终得到了等待管道完成的脚本的"额外"副本,这样它就可以收集输出并将其返回给原始剧本.
我们将使用(...)
在子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"
Run Code Online (Sandbox Code Playgroud)
在我的运行中产生输出:
Start
30885
1
2
end
Run Code Online (Sandbox Code Playgroud)
所以我们可以看到pgrep test.sh
在子shell 中运行只找到test.sh的单个实例,即使该子shell是管道本身的一部分.但是,如果子shell包含一个管道,那么我们得到脚本的分叉副本,等待管道完成