How to check if another instance of my shell script is running

后端 未结 15 1990
执念已碎
执念已碎 2020-12-01 00:35

GNU bash, version 1.14.7(1)

I have a script is called \"abc.sh\" I have to check this from abc.sh script only... inside it I have written f

相关标签:
15条回答
  • 2020-12-01 01:18

    I have found that using backticks to capture command output into a variable, adversly, yeilds one too many ps aux results, e.g. for a single running instance of abc.sh:

    ps aux | grep -w "abc.sh" | grep -v grep | wc -l
    

    returns "1". However,

    count=`ps aux | grep -w "abc.sh" | grep -v grep | wc -l`
    echo $count
    

    returns "2"

    Seems like using the backtick construction somehow temporarily creates another process. Could be the reason why the topicstarter could not make this work. Just need to decrement the $count var.

    0 讨论(0)
  • 2020-12-01 01:21

    Here's one trick you'll see in various places:

    status=`ps -efww | grep -w "[a]bc.sh" | awk -vpid=$$ '$2 != pid { print $2 }'`
    if [ ! -z "$status" ]; then
        echo "[`date`] : abc.sh : Process is already running"
        exit 1;
    fi
    

    The brackets around the [a] (or pick a different letter) prevent grep from finding itself. This makes the grep -v grep bit unnecessary. I also removed the grep -v $$ and fixed the awk part to accomplish the same thing.

    0 讨论(0)
  • 2020-12-01 01:31

    I you want the "pidof" method, here is the trick:

        if pidof -o %PPID -x "abc.sh">/dev/null; then
            echo "Process already running"
        fi
    

    Where the -o %PPID parameter tells to omit the pid of the calling shell or shell script. More info in the pidof man page.

    0 讨论(0)
  • 2020-12-01 01:32

    I find the answer from @Austin Phillips is spot on. One small improvement I'd do is to add -o (to ignore the pid of the script itself) and match for the script with basename (ie same code can be put into any script):

    if pidof -x "`basename $0`" -o $$ >/dev/null; then
        echo "Process already running"
    fi
    
    0 讨论(0)
  • 2020-12-01 01:32

    Definitely works.

    if [[ `pgrep -f $0` != "$$" ]]; then
            echo "Exiting ! Exist"
            exit
    fi
    
    0 讨论(0)
  • 2020-12-01 01:33

    The cleanest fastest way:

    processAlreadyRunning () {
        process="$(basename "${0}")"
        pidof -x "${process}" -o $$ &>/dev/null
    }
    
    0 讨论(0)
提交回复
热议问题