[英]PS command returns different format in a shell script
This is the content of a.sh
: 这是
a.sh
的内容:
#!/bin/bash
echo $(ps ax |wc -l)
This is what I see on my shell: 这是我在外壳上看到的:
$ ps ax |wc -l
109
$ ./a.sh
111
Obviously those 2 numbers should be the same. 显然,这两个数字应该相同。 The difference seems the way
ps
formats the results is different in the bash script, but I can't figure out why? 差异似乎是在bash脚本中
ps
格式化结果的方式不同,但是我不知道为什么吗? This is on a CentOS 7 system. 这是在CentOS 7系统上。
EDIT: 编辑:
This isn't just a matter of additional shell processes being spawned as some comments make it sound. 这不仅是由于一些注释使之听起来而产生的其他shell进程的问题。 Take this example:
举个例子:
#!/bin/bash
echo "$(ps -ax |grep httpd)"
The output: 输出:
$ ./a.sh
10052 ? S 0:01 /usr/sbin/httpd -DFOREGROUND
10230 ? Ss 0:02 /usr/sbin/httpd -DFOREGROUND
13790 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
13839 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
13848 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
13852 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
16015 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
18805 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
18865 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
18866 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
18886 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
$ ps ax|grep httpd
10052 ? S 0:01 /usr/sbin/httpd -DFOREGROUND
10230 ? Ss 0:02 /usr/sbin/httpd -DFOREGROUND
13790 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
13839 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
13848 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
13852 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
16015 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
18805 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
18865 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
18866 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
18886 ? S 0:00 /usr/sbin/httpd -DFOREGROUND
20565 pts/0 R+ 0:00 grep --color=auto httpd
So here the shell script returns less lines than the bash prompt command does. 所以这里的shell脚本返回比bash提示符的命令行做少 。
Looks right to me. 在我看来不错。 When you run
./a.sh
, two new processes will be created -- the new bash
shell and the bash
subshell created by the $(...)
. 当您运行
./a.sh
,将创建两个新进程-新的bash
shell和$(...)
创建的bash
子shell。 (Not the echo, like I wrote earlier. Even using /usr/bin/echo
, that would not get run until after the ps
, so would not be counted.) (不是回声,就像我之前写的那样。即使使用
/usr/bin/echo
,也要等到ps
之后才能运行,因此不算在内。)
$ ps -ax -o pid,cmd | wc -l
267
$ cat a.sh
#!/bin/bash
echo $( ps -ax -o pid,cmd | wc -l )
$ ./a.sh
269
Now to get rid of the extra subshell: 现在摆脱多余的子shell:
$ cat b.sh
#!/bin/bash
ps -ax -o pid,cmd | wc -l
[jack@marta ~]$ ./b.sh
268
Now, get rid of the extra process by not starting a new shell: 现在,通过不启动新的shell来摆脱额外的过程:
$ source b.sh
267
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.