It think that your logic is more like:
if [ ! -e lockfile ]; then
touch lockfile
do_work
rm lockfile
fi
But be aware that even this is not enough. Indeed, it paves the way for subtle bugs. Since the whole thing is not atomic, a second process might as well start just after the if
clause but before the touch
one.
A less naive implementation of your idea would attempt at atomicity of the lock-acquiring operation. This can be done in Bash.
A possible solution is the noclobber
option, which forbids writing to an already existing file, thereby accomplishing both the if
clause and the touch
command in a more-of-an-atomic fashion.
My lock-acquiring code would then look like this:
if ! ( set -o noclobber; echo > lockfile ) exit