Just putting this here because it helped me out today. How do you ensure (on #linux ) that only one instance of a script is running, without race conditions or having to clean up lock files? Simple:
#!/bin/sh
(
if ! flock -n -x 0
then
echo "$$ cannot get flock"
exit 0
fi
echo "$$ start"
sleep 10 # for testing. put the real task here
echo "$$ end"
) < $0
#!/bin/sh
(
if ! flock -n -x 0
then
echo "$$ cannot get flock"
exit 0
fi
echo "$$ start"
sleep 10 # for testing. put the real task here
echo "$$ end"
) < $0
View 21 previous comments
- +Randal L. Schwartz Unless something else is using that FD, right? I've seen people do weird things with 3 and up for logging purposes.Aug 19, 2013
- Yeah, here's the updated version (tested):
#!/bin/sh
(
if ! flock -n -x 200
then
echo "$$ cannot get flock"
exit 0
fi
echo "$$ start"
sleep 10 # real work would be here
echo "$$ end"
) 200< $0Aug 19, 2013 - I love the $0 trick.Aug 22, 2013
- I like it, but let's abstract it for reuse by using exec to avoid being wrapped in a subshell and extracting that into another script we'll call only-one.
#!/bin/bash
exec 200< $0
if ! flock -n 200; then
echo "there can be only one"
exit 1
fi
Now when we want a script to be single use we simply source it:
#!/bin/bash
source only-one
echo "${BASHPID} working"
sleep 10
And we're good to go. Nice trick.Sep 8, 2013 - Oooh! Awesome!Sep 8, 2013
- let's call it highlander.sh ;-)
You source highlander.sh and you are guaranteed to be the only one. ;-)Sep 10, 2013
Add a comment...