Adooo
Adooo

Reputation: 670

bash command substitution's result not consistent

I have a script.

cat /root/test/ddd.sh

#!/bin/bash
s=/root/test/ddd.sh
ps -ef | grep $s | grep -v grep
result=$(ps -ef | grep $s | grep -v grep | wc -l)
echo $result

when i execute it, the result is weird, it shows that there is two line matched.

[root@l2 test]# /root/test/ddd.sh
root     15361 15032  0 09:52 pts/18   00:00:00 /bin/bash         /root/test/ddd.sh
2

Upvotes: 1

Views: 65

Answers (1)

Tanktalus
Tanktalus

Reputation: 22254

That's because you're running a subshell. That is, the $(...) piece causes bash to fork, thereby creating two (nearly) identical processes. By identical, I mean basically everything except for process ID, parent process ID, return code from the fork, and I can't think of anything else. But one thing that does remain the same for sure is the command line. Both of them will be "/bin/bash /root/test/ddd.sh". So, inside the result=$(...), there will be exactly one extra process that matches.

You can see this, for example, by removing the | wc -l piece at the end of your $(...), and, to make it more readable, enclose the echo's argument in quotes:

result="$(ps -ef | grep $s | grep -v grep)"
echo "$result"

Here you will see that there are two bashes, and the PPID of one is the PID of the other, showing the parent-child relationship.

Upvotes: 2

Related Questions