You can do this with the flock
utility. You just need to get flock
to use a separate read-only file descriptor, i.e. open the file twice. E.g. to sort a file using a intermediate temporary file:
(
flock -x -w 10 100 || exit 1
tmp=$(mktemp)
sort <"$file" >"$tmp"
cat "$tmp" > "$file"
rm -f "$tmp"
) 100<"$file"
flock
will issue the flock()
system call for your file and block if it is already locked. If the timeout is exceeded then the script will just abort with an error code.