msgbartop
MAC OS X, Linux, Windows and other IT Tips and Tricks
msgbarbottom

14 Jan 16 Preventing a bash script from running concurrently

Introduction: In order to prevent a bash script instance from running more than once concurrently, here is a small tip on how to write the script.

Script template:
#!/bin/bash
# Prevents that an instance of the script starts while another instance of it is still running
scriptname=$(basename $0)
lockfile="/tmp/${scriptname}.lock"
if [ -e $lockfile ]; then exit 1 ; fi
touch $lockfile.lock
# Delete lock file if CTRL-C typed from the keyboard
trap 'rm $lockfile ; exit' SIGINT SIGQUIT
#----------------------------------
# ############ Put your script code here #####################
#----------------------------------
# delete the lock file
rm $lockfile
# .eof

Leave a Reply

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

%d bloggers like this: