简体   繁体   中英

PS command returns different format in a shell script

This is the content of 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? This is on a CentOS 7 system.

EDIT:

This isn't just a matter of additional shell processes being spawned as some comments make it sound. 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.

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 $(...) . (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.)

$ 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:

$ 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:

$ source b.sh
267

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM