Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script counting instances of itself wrongly

Tags:

linux

grep

bash

ps

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.

like image 557
roberto06 Avatar asked Dec 23 '22 23:12

roberto06


1 Answers

This is a standard issue with greping the output of ps.

One solution is to add some square brackets around a character

nb=$(ps -aux | grep '[c]ount_itself.sh')

This means that your grep instance doesn't match itself, because the name of the process with its arguments contains square brackets but the pattern that it matches doesn't.

As mentioned in the comments, you should use double quotes around your variables in order to preserve whitespace.

The reason why you have appear to have two instances of the same shell in your results is that the command substitution is executed within a subshell. For details on only showing the parent process, see this question.

like image 112
Tom Fenech Avatar answered Jan 02 '23 23:01

Tom Fenech