Bash script invalid instance counting

I created a bashscript that counts running instances of itself.

Here it is (in this example I am showing instances, not counting them with wc -l):

#!/bin/bash
nb=`ps -aux | grep count_itself.sh`
echo "$nb"
sleep 20

(Of course my script is called count_itself.sh)

Performing it, I expect it to return two rows, but 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

Executing it with a flag &(i.e. in the background and manually executing a bit ps -aux), it returns two 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 is the execution ps -auxinside the script returning one line more than expected?

Or, in other words, why was the process with id 16226created in my first example?

EDIT (since most people seem to misunderstand my question):

, bash /bin/bash ./count_itself.sh, grep count_itself.sh.

2:

, , /bin/bash ./count_itself.sh script .

+4
4
, , , @TomFenech, :
#!/bin/bash
nb=$(ps f | grep '[c]ount_itself.sh' | grep -v '    \\_')
echo "$nb"
sleep 20

:

root@myserver:/# ./count_itself.sh
17725 pts/1    S+     0:00  \_ /bin/bash ./count_itself.sh

bg:

root@myserver:/# ./count_itself.sh &
[1] 17733
root@myserver:/# ./count_itself.sh
17733 pts/1    S      0:00  \_ /bin/bash ./count_itself.sh
17739 pts/1    S+     0:00  \_ /bin/bash ./count_itself.sh

( , ):

  • ps f
  • grep '[c]ount_itself.sh' count_itself.sh

17808 pts/1    S+     0:00  \_ /bin/bash ./count_itself.sh
17809 pts/1    S+     0:00      \_ /bin/bash ./count_itself.sh
  • grep -v ' \\_' , 4 ( ), \_,
+1

grep ps.

-

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

, grep , , , , .

, , .

, , , . . .

+4

, -, fork . , (, , ), script $(...).

:

$ cat test.sh 
#!/bin/bash

a=1
b="$(a=2; echo abc)"
echo "a=$a"
echo "b=$b"
$ ./test.sh 
a=1           # Note that the variable 'a' preserved its value
b=abc

script.

, , script ( ), .

One hacky solution is to have the script create /tmp/your_script_namea PID file at the specified location (for example, in ) when called and delete it after completion.

+2
source

I suggest the following way:

Exclude the whole process that the parent himself:

 ps --pid $$ -N -a | grep count_itself.sh

This means that all commands that are parent are not themselves (this excludes your grep process and the fork process to execute the oncoming sentence)

+2
source

Source: https://habr.com/ru/post/1661043/


All Articles