NRS2000
NRS2000

Reputation: 115

How do exec and flock work together in bash script

Bash Script:

#!/bin/bash
...
exec {LOCK} > foo.out
flock -x ${LOCK}
...

I understand that exec without an argument simply redirects all the output of the current shell to the foo.out file. Questions:

  1. What does the first argument to exec {LOCK} mean, given that it seems to have a special significance because it is in curly braces (but not ${...}).

  2. What is the value of ${LOCK} and where did it come from (I don't think that I defined this variable)?

Upvotes: 1

Views: 2697

Answers (2)

NRS2000
NRS2000

Reputation: 115

Here is what I finally figured out:

exec {LOCK}> foo.out changes stdout of the current shell to the file foo.out. The fd for the open file is set the variable ${LOCK}. Setting fd to the {LOCK} variable is a feature of bash.

flock -x ${LOCK} is simply locking using the file descriptor.

Upvotes: 0

that other guy
that other guy

Reputation: 123570

This is not valid or useful bash. It will just result in two different error messages.

Instead, the intended code was this:

#!/bin/bash
...
exec {LOCK}> foo.out
flock -x ${LOCK}
...

It uses:

  1. {name}> to open for writing and assign fd number to name
  2. exec to apply the redirection to the current, keeping the fd open for the duration of the shell
  3. flock to lock the assigned fd, which it will inherit from the current shell

So effectively, it creates a mutex based on the file foo.out, ensuring that only one instance is allowed to run things after the flock at a time. Any other instances will wait until the previous one is done.

Upvotes: 1

Related Questions