I would like to allow only one instance of a script to run at any moment.
I've tried the following solution to count the instances but the result is always the number of running instances plus one and I can't find the problem
ps -ef | grep $0 | sed '/^$/ d' | sed '/grep/ d' | wc -l
Another fairly robust solution is to create a lock file:
#!/bin/ksh
# check for existence of a lock file
# if the file exists make sure the pid that
# created it is still running then exit.
if [ -e /tmp/myshellscript.lock ]; then
pid=`cat /tmp/myshellscript.lock`
ps -p "$pid" >/dev/null 2&>1
# somebody else is running the script ?
if [ $? -eq 0]; then
echo "another processi is running - try again later"
exit 1
fi
# put the current process as owner of the lock
echo "$$" > /tmp/myshellscript.lock
else
# no file found - make one, own the lock,too.
echo "$$" > /tmp/myshellscript.lock
chmod 777 /tmp/myshellscript.lock
fi
...
.....
# last lines of script - release lock file
rm -f /tmp/myshellscript.lock
exit 0