#!/bin/bash # filelock--A flexible file locking mechanism setglobal retries = '"10'" # Default number of retries setglobal action = '"lock'" # Default action setglobal nullcmd = $[which true] # Null command for lockfile while getopts "lur:" opt { match $opt { with l setglobal action = '"lock'" with u setglobal action = '"unlock'" with r setglobal retries = $OPTARG } } shift $shExpr('$OPTIND - 1') if test $Argc -eq 0 { # Output a multi-line error message to stdout. cat << """ >&2 Usage: $0 [-l|-u] [-r retries] LOCKFILE Where -l requests a lock (the default), -u requests an unlock, -r X specifies a max number of retries before it fails (default = $retries). """ > !2 Usage: $0 [-l|-u] [-r retries] LOCKFILE Where -l requests a lock (the default), -u requests an unlock, -r X specifies a max number of retries before it fails (default = $retries). EOF exit 1 } # Ascertain if we have the lockfile command. if test -z $[which lockfile | grep -v '^no ] { echo "$0 failed: 'lockfile' utility not found in PATH." > !2 exit 1 } if test $action = "lock" { if ! lockfile -1 -r $retries $1 !2 > /dev/null { echo "$0: Failed: Couldn't create lockfile in time" > !2 exit 1 } } else { # Action = unlock. if test ! -f $1 { echo "$0: Warning: lockfile $1 doesn't exist to unlock" > !2 exit 1 } rm -f $1 } exit 0