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

后端 未结 15 1991
执念已碎
执念已碎 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:34

    I create a temporary file during execution.

    This is how I do it:

    #!/bin/sh
    # check if lock file exists
    if [ -e /tmp/script.lock ]; then
      echo "script is already running"
    else
    # create a lock file
      touch /tmp/script.lock
      echo "run script..."
    #remove lock file
     rm /tmp/script.lock
    fi
    
    0 讨论(0)
  • 2020-12-01 01:35

    [ "$(pidof -x $(basename $0))" != $$ ] && exit

    https://github.com/x-zhao/exit-if-bash-script-already-running/blob/master/script.sh

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

    pidof wasn't working for me so I searched some more and came across pgrep

    for pid in $(pgrep -f my_script.sh); do
        if [ $pid != $$ ]; then
            echo "[$(date)] : my_script.sh : Process is already running with PID $pid"
            exit 1
        else
          echo "Running with PID $pid"
        fi  
    done
    

    Taken in part from answers above and https://askubuntu.com/a/803106/802276

    0 讨论(0)
提交回复
热议问题