To lock a file:
exec 3>filename
To release a lock:
exec 3>&-
You can also do this as the herd page describes:
{ flock -x 3 ...other stuff here... } 3>filename
... and in this case, the file is automatically closed when you exit the block. (Here you can also use a subshell using ( ) rather than { } , but this should be a deliberate solution - since subshells have performance limitations and modifications to region variables and other state changes for themselves).
If you are using a sufficiently new version of bash, you do not need to manually manage the file descriptor numbers:
... now for your function we need associative arrays and automatic FD distribution (and so that the same file is locked and unlocked from different paths, GNU readlink) t with older versions of bash:
declare -A lock_fds=()
If you are on a platform where GNU readlink is not available, I would suggest replacing the readlink -f call with the realpath from sh-realpath from Michael Kropat (relying only on the widely available readlink function, not the GNU extensions).
source share