How to check in a bash script if something is running and exit if it is

后端 未结 9 1943
悲&欢浪女
悲&欢浪女 2021-02-06 00:24

I have a script that runs every 15 minutes but sometimes if the box is busy it hangs and the next process will start before the first one is finished creating a snowball effect.

9条回答
  •  盖世英雄少女心
    2021-02-06 00:57

    This is how I do it in one of my cron jobs

    lockfile=~/myproc.lock
    minutes=60
    if [ -f "$lockfile" ]
    then
      filestr=`find $lockfile -mmin +$minutes -print`
      if [ "$filestr" = "" ]; then
        echo "Lockfile is not older than $minutes minutes! Another $0 running. Exiting ..."
        exit 1
      else
        echo "Lockfile is older than $minutes minutes, ignoring it!"
        rm $lockfile
      fi
    fi
    
    echo "Creating lockfile $lockfile"
    touch $lockfile
    

    and delete the lock file at the end of the script

    echo "Removing lock $lockfile ..."
    rm $lockfile
    

提交回复
热议问题