I've created a bash
script which counts launched instances of itself.
Here it is (in this example, I'm showing the instances rather than counting them with wc -l
) :
#!/bin/bash
nb=`ps -aux | grep count_itself.sh`
echo "$nb"
sleep 20
(Of course, my script is named count_itself.sh
)
Upon executing it, I expect it to return two lines, but it returns three :
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
Upon executing it with the &
flag (i.e. in background, and manually executing the ps -aux
bit, it returns two, which is what I want :
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
My question is : Why does the ps -aux
execution inside the script return one line more than expected ?
Or, in another words, why is the process with the id 16226
created in my first example ?
EDIT (as most people seem to misunderstand my question) :
I'm wondering why the bash
execution returns two instances of /bin/bash ./count_itself.sh
, not why it returns grep count_itself.sh
.
EDIT 2 :
And of course, I'm looking for a way to avoid this behaviour and have the script return /bin/bash ./count_itself.sh
only once.