Manage locking into bash scripts

From WikiOAR

Jump to: navigation, search

Every bash script started fron cron should begin like this

(Using lockfile-progs under Debian. For other distribs, you can use "lockfile -r3 -l 43200 $LOCK" often found into the sendmail package)

#!/bin/bash
set -e

# Locking
LOCK=/var/lock/`basename $0`
lockfile-create $LOCK || exit 2
lockfile-touch $LOCK &
BADGER="$!"
function remove_lock {
  kill "${BADGER}" 2>/dev/null || true
  lockfile-remove $LOCK
}

# Exit trap function
function exit_on_error {
  echo "Exiting on error..."
  remove_lock
  exit 1
}

# Exit on kill
function exit_on_kill {
  echo "Killed, exiting..."
  remove_lock
  exit 1
}

# Exit normaly
function exit_on_end {
  echo "Exiting..."
  remove_lock
  exit 0
}

trap exit_on_kill KILL
trap exit_on_error ERR
trap exit_on_end QUIT TERM EXIT INT


## SCRIPT STARTS HERE ##

Why?

Because if you run a script periodically using cron, you never know if your script has ended before the next period when the script is ran again and in case of a deadlock, you may overflow your system.

Personal tools