Bash Flock Single Instance Lock

Ensure only one script instance runs with flock file locking to prevent concurrent execution.

BashSecurity Boundaries

Code

snippet
#!/bin/bash
LOCKFILE="/var/run/myscript.lock"
exec 9>"$LOCKFILE"
if ! flock -n 9; then
  echo "another instance is running" >&2
  exit 1
fi
echo "acquired lock, running"
sleep 30
echo "done"