I have a shell script.
How can use some kind of locking mechanism to ensure that the script is not being executed by two people
at the same time?
You can use setfacl command to set acl on the file that what user can run it.That what i think maby be some other have better idea
#!/bin/ksh
lockit()
{
[[ -w /tmp/lockfile ]] || > /tmp/lockfile
let count=0
echo 'checking lock...'
while [[ -s /tmp/lockfile ]]
do
sleep 30
count=#(( count + 1 ))
if [[ count -eq 10 ]] ; then
echo 'cannot obtain lock'
exit 1
fi
done
echo "$$" > /tmp/lockfile
echo 'got lock'
}
unlock()
{
> /tmp/lockfile
}
# main --------------------------
lockit
trap '> /tmp/lockfile; kill -9 $$ ' EXIT HUP INT
. /path/to/myscript.sh
STATUS=$?
unlock
trap ' ' EXIT
exit $STATUS
Put your scriptname inside this type of script. If your script has trap commands they may override the ones here. This is just meant as a simple starting point.
That is really helpful
Thanks a lot