I have been working on using "flock"/file lock to prevent two instances of a bash script from being executed. Below is a simplified version of what I have to illustrate the flock part. It works as it is set up there below however the piece I am trying to figure out is how to get it to output to /var/log/messages ONLY when a 2nd instance of the script is attempted to run and subsequently errors out. If I put some "logger" command in the script then it will just run every single time regardless of whether or not I wanted it to. I believe I need something after the || but just what I am not sure. I tried putting ( ) around the piece after the || but that seems to mess with the script itself and actually allowed 2 or more instances to runat the same time so I don't think I did that right.
I think you did it correctly, and it should have worked.
Using { } instead of ( ) can eventually save a sub-shell. Note that the closing } must be on a new line or preceded by a semicolon.
You could also try this full manual approach (as i've overseen the 'flock' command, but want to share this anyway):
#!/bin/bash
#
# Vars
#
PID=$$
LOCK=/tmp/${0##/*}.lock
LOCK_USED=false
#
# Reset lockfile upon exit
#
trap "echo > $LOCK" ERR ABRT KILL
#
# Preps
#
if [ ! -f $LOCK ]
then echo "No lockfile found..."
touch $LOCK
elif [ -s $LOCK ]
then echo "Lockfile found, and empty"
else echo "Lockfile found, and/or non-empty = busy"
LOCK_USED=true
fi
#
# Action
#
if $LOCK_USED
then echo "Aborting, script is already running at PID: $(<$LOCK_FILE)"
exit 1
else # Save the current PID in the file
echo $PID > $LOCK
fi
#
# Actual script
#
echo "Do your stuff..."
Hope this helps
EDIT:
When i'm calling RudiC's solution, very close to the origin, i'm having a 5 sec delay if the script is already running.
Likewise in the main execution, it takes 1 min 5 sec - quite a long time to just check wether there is a lock or not, dont you think?
I assume that is caused by will (on purpose) as flock -w 5 is used, personally, i think it is too long for testing.