cjb
cjb

Reputation: 25

Can I combine flock and source?

I'd like to source a script (it sets up variables in my shell):

source foo.sh args

But under flock so that only one instance operates at a time (it does a lot of disk access which I'd like to ensure is serialized).

$ source flock lockfile foo.sh args
-bash: source: /usr/bin/flock: cannot execute binary file

and

$ flock lockfile source foo.sh args
flock: source: Success

don't work.

Is there some simple syntax for this I'm missing? Let's assume I can't edit foo.sh to put the locking commands inside it.

Upvotes: 1

Views: 295

Answers (1)

FatalError
FatalError

Reputation: 54591

You can't source a script directly via flock because it is an external command and source is a shell builtin. You actually have two problems because of this:

  • flock doesn't know any command called source because it's built into bash
  • Even if flock could run it, the changes would not affect the state of the calling shell as you'd want with source because it's happening in a child process.

And, passing flock to source won't work because source expects a script. To do what you want, you need to lock by fd. Here's an example

#!/bin/bash

exec 9>lockfile
flock 9
echo whoopie
sleep 5
flock -u 9

Run two instances of this script in the same directory at the same time and you will see one wait for the other.

Upvotes: 2

Related Questions