Skip to content

Instantly share code, notes, and snippets.

@jpclipffel
Last active January 25, 2024 05:07
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save jpclipffel/0b8f470be029fc9e3f07 to your computer and use it in GitHub Desktop.
Save jpclipffel/0b8f470be029fc9e3f07 to your computer and use it in GitHub Desktop.
Bash flock example
#!/bin/bash
#
# Bash `flock` example.
# Works on: Linux, BSD
# Doesn't work on: MacOS
# The file which represent the lock.
LOCKFILE="`basename $0`.lock"
# Timeout in seconds.
TIMEOUT=2
# Create the lockfile.
touch $LOCKFILE
# Create a file descriptor over the given lockfile.
exec {FD}<>$LOCKFILE
# Try to lock the file descriptor $FD during $TIMEOUT seconds.
# If it failsm exit with an error.
# Otherwise, the lock is acquired and implicitely droped at the end of the script.
if ! flock -x -w $TIMEOUT $FD; then
echo "Failed to obtain a lock within $TIMEOUT seconds"
echo "Another instance of `basename $0` is probably running."
exit 1
else
echo "Lock acquired"
fi
@valp124
Copy link

valp124 commented Feb 5, 2020

Stumbled upon this by accident. Here's the answer to the question:

https://unix.stackexchange.com/questions/226164/what-does-exec-fd-dev-watchdog-do-in-bash

@nkh
Copy link

nkh commented Jun 9, 2023

also found flock man page

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment