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
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
dbain
  • 77

2 Answers2

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.

agc
  • 7,223
1

Using pgrep ...

#!/bin/bash

PNAME=$(basename "$0")

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

(( COUNT > 1 ))  &&  echo "$0 already running, exiting..."                                                           
fpmurphy
  • 4,636