Last active
July 11, 2024 10:56
-
-
Save jpclipffel/0b8f470be029fc9e3f07 to your computer and use it in GitHub Desktop.
Bash flock example
This file contains 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 |
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
also found flock man page
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello,
I very much wonder where you found in the docs the syntax and semantics for the following stanza:
exec {FD}<>$LOCKFILE
This seems un{,der}documented in 'exec' builtin command.
Please, don't hesitate to link to redirection operators, to "{3..8}" sequence expansion ( why just {FD} ? ), and to builtin 'exec' redirection syntax reference/docs , and tell us why " {FD} " means bash must assign to variable named 'FD' the following gained file descriptor.
excerpt : exec: exec [-cl] [-a nom] [commande [arguments ...]] [redirection ...]
Could you light up our candle?
Yours, Kindly,
Val'