utility

flock

Acquire an advisory lock on a descriptor or file. -n fails without waiting; -w bounds wait. All writers must cooperate; filesystem behavior varies.

Formal Syntax & Structure

bash syntaxbash
flock -x [-n|-w seconds] fd; flock -n file command

Parameters & Attributes

NameTypeDescription
fd or filedescriptor or pathStable owned lock resource.

Return Value

exit status

Acquire an advisory lock on a descriptor or file. -n fails without waiting; -w bounds wait. All writers must cooperate; filesystem behavior varies.

Working Example

Example Snippetbash
exec 9> shared.lockflock -x -w 1 9 || exit 1if flock -n shared.lock true; then    printf 'unexpected\n'    exit 1else    rc=$?    [[ $rc == 1 ]] || exit 1    printf 'busy\n'fiexec 9>&-flock -n shared.lock printf 'available\n'
Bash Reference