Skip to main content
4 of 4
missing quotes and --, errors to stderr, use standard function definition syntax instead of ksh one
Stéphane Chazelas
  • 584.8k
  • 96
  • 1.1k
  • 1.7k

To add to Bruce Ediger's answer, and inspired by this answer, you should also add more smarts to the cleanup to guard against script termination:

#Remove the lock directory
cleanup() {
    if rmdir -- "$LOCKDIR"; then
        echo "Finished"
    else
        echo >&2 "Failed to remove lock directory '$LOCKDIR'"
        exit 1
    fi
}

if mkdir -- "$LOCKDIR"; then
    #Ensure that if we "grabbed a lock", we release it
    #Works for SIGTERM and SIGINT(Ctrl-C) as well in some shells
    #including bash.
    trap "cleanup" EXIT

    echo "Acquired lock, running"

    # Processing starts here
else
    echo >&2 "Could not create lock directory '$LOCKDIR'"
    exit 1
fi