exit-post-hook-unlock.sh: use a trap to release the lock
[experiments/hook-lock.git] / exit-post-hook-unlock.sh
index d618346..1db555f 100755 (executable)
 set -e
 
 LOCKDIR=/run/lock/mylockdir
+[ -d "$LOCKDIR" ] || exit 0
+
 LOCKPID=$(cat "$LOCKDIR/pid")
 [ "$LOCKPID" = $PPID ] || { echo "The enter script was launched from another process. Unlocking aborted." >&2; exit 1; }
 
-# Do stuff here
+# Use a trap to release the lock even if the commands below fail.
+trap 'rm -rf "$LOCKDIR"' EXIT
+trap 'exit 2' HUP INT QUIT PIPE TERM
 
-rm -rf "$LOCKDIR"
+# Do stuff here.