Lock shellscript process under Unix based systems

Today I ran again into a common problem when dealing with cron based scipts that run concurrently. That’s why I had to lock shellscript process until it is finished before starting the next executing round.
On Unix based systems like Linux you can achieve that with flock. flock binds a file descriptor to a certain lock file.
There are plenty ways to use it for our mentioned problem.
I got rid of concurrently running processes caused by multiple script instandes running at the same time by using this snippet:

!#/bin/bash
exec 9>/path/to/lock/file
if ! flock -n 9  ; then
    echo "Hey dude! There is already another instance running! Be more patient!!!";
    exit 1
fi

As you can see, this script echos a error message until the lock 9 file ‘/path/to/lock/file‘ exists.  It will be removed automatically when the script was executed.

More information about  lock shellscript process

For more information about this mighty command,  please consult the man page.

Leave a Reply

Your email address will not be published. Required fields are marked *

 

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