== How to do locking in shell scripts To do simple locking in shell scripts, you need an atomic system call that fails if the target already exists, and that is directly exposed in a utility program. Ignoring for a moment [[what System V did to _ln_ SystemVLn]], there are two good candidates on modern Unix systems: _link(2)_ and _mkdir(2)_. _Mkdir_ is actually the better of the two (because you don't have to fiddle around with temporary files), but _ln_ is the more common one, probably for two reasons: # with _mkdir_ you can't atomically associate some extra information, like a PID, with the lock. You can put a PID file inside the directory, but there will be a time when it doesn't exist although you have the lock. # there was no _mkdir(2)_ system call in V7; it was only added in UCB BSD, and didn't make it into System V until fairly late. So for a fair time _mkdir_ wasn't actually suitable for this, and everyone got into the habit of using _ln_. General locking with _mkdir_ is simple: > mkdir LOCK 2>/dev/null || exit 0 > echo running locked > rmdir LOCK Locking with _ln_ ([[ignoring System V SystemVLn]]) is somewhat more complicated: > echo $$ >$$ > if ln $$ LOCK 2>/dev/null; then > echo running locked > rm $$ LOCK > else > rm $$ > fi In both cases you really want a private directory for the locks. If you have to use a shared directory like _/tmp_, I believe the _ln_ approach is the only one that can stand up to hostile attacks (provided that you use something like _mktemp_ to securely create the temporary file).