Bash Scripts with flock

If you have a cronjob that runs every periodically, it’s possible the jobs will run into each other. But, you can prevent this by wrapping your bash shell around flock. Only one program can run. If the bash script tries to start up a 2nd time, it will wait for 10s and if it still can’t get the lock, it will exit.

This will prevent two or more copies of your program from running.

    # Wait 10s for lock on /var/lock/.myjob.exclusivelock
    flock -x -w 10 200 || exit 1
# Put long running job here
)  200>/var/lock/.myjob.exclusivelock