• Uncategorized

About bash : create-a-lock-file-in-bash-to-avoid-duplicate-execution

Question Detail

I’m not very good on bash I’ve been modifying a code to create a lock file so a cron don’t execute a second time if the first process hasn’t finish.

LOCK_FILE=./$(hostname)-lock
(set -C; : > $LOCK_FILE) 2> /dev/null
if [ $? != "0" ]; then
   echo "already running (lock file exists); exiting..."
exit 1
fi

trap 'rm $LOCK_FILE' INT TERM EXIT

when I run it for the first time I get the message already running as if the file already existed.

Perhaps I’m missing something

Question Answer

#!/bin/sh

(
  # Wait for lock on /tmp/lock

  flock -x -w 10 200 || exit 127 # you can use or not use -w

  #your stuff here

) 200> /tmp/lock

check man page flock.

This is the tool for you.
And it comes with example in man page 🙂

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.