1

I am trying to find number of runs of a script but its always 2 even though only one running.

sh 11.sh
1
 11.sh already running,exiting..

here is code.

ps -ef | grep -v grep | grep -c "$0"
if [[ `ps -ef | grep -v grep | grep -c "$0"` -gt "1" ]]; then
            `echo " $0 already running,exiting.."`
fi
1
  • 4
    Consider using pgrep instead.
    – Kusalananda
    Oct 22, 2017 at 20:57

2 Answers 2

1

Using pgrep ...

#!/bin/bash

PNAME=$(basename "$0")

COUNT=$(pgrep -c -x  $PNAME)

(( COUNT > 1 ))  &&  echo "$0 already running, exiting..."                                                           
1

Considering only a single instance of 11.sh running, and given this 11.sh:

n=`ps -ef | grep -wc "$0"` n=$((n-2))
echo $n
[ $n -gt "1" ] &&  echo " $0 already running,exiting.."

Running sh 11.sh outputs:

 1

The backticks and the grep add two more ps lines. Since we know the number is 2, just subtract n-2 to get the correct number.

2
  • This code can give false positives. For example, grep will match 211.sh or murphy11.sh or 11.shar
    – fpmurphy
    Oct 23, 2017 at 4:51
  • @fpmurphy1, Thanks. Added a -w to grep.
    – agc
    Oct 23, 2017 at 5:26

Not the answer you're looking for? Browse other questions tagged .