-
-
Save 0xack13/2a404910efa1d2eb1df64532495d41f4 to your computer and use it in GitHub Desktop.
Bash flock example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment