bashgreppssubshell

How to find the number of instances of current script running in bash?


I have the below code to find out the number of instances of current script running that is running with same arg1. But looks like the script creates a subshell and executes this command which also shows up in output. What would be the better approach to find the number of instances of running script ?

$cat test.sh
#!/bin/bash

num_inst=`ps -ef | grep $0 | grep $1 | wc -l`
echo $num_inst
$ps aux | grep test.sh | grep arg1 | grep -v grep | wc -l
0
$./test.sh arg1 arg2
3
$

I am looking for a solution that matches all running instance of ./test.sh arg1 arg2 not the one with ./test.sh arg10 arg20


Solution

  • The reason this creates a subshell is that there's a pipeline inside the command substitution. If you run ps -ef alone in a command substitution, and then separately process the output from that, you can avoid this problem:

    #!/bin/bash
    
    all_processes=$(ps -ef)
    num_inst=$(echo "$all_processes" | grep "$0" | grep -c "$1")
    echo "$num_inst"
    

    I also did a bit of cleanup on the script: double-quote all variable references to avoid weird parsing, used $() instead of backticks, and replaced grep ... | wc -l with grep -c.

    You might also replace the echo "$all_processes" | ... with ... <<<"$all_processes" and maybe the two greps with a single grep -c "$0 $1":

    ...
    num_inst=$(grep -c "$0 $1" <<<"$all_processes")
    ...