1

Example with the command-line tool flock.
The documentation just defines the syntax:

flock [options] <file> -c <command>

But -c seems not to be mandatory. This line executes a program if locking of a file is possible (the '-n' switch disable wait for lockfile release):

flock -n lockfile.lck echo "File is Locked"

I would like, instead, to make a script like:

flock -n $TMP/lockfile.lck (
        echo "Congratulations:"
        echo "you have acquired the lock of the file"
        )

As you can see, it is nearly the same, but executing more than one line.
Is it possible?

And, for the case when locking is not possible:

flock -n lockfile.lck echo "Lock acquired" || echo "Could not acquire lock"

I would like to know if it can be implemented something like :

flock -n $TMP/lockfile.lck (
        echo "Congratulations:"
        echo "you have acquired the lock of the file"
        ) || (
        echo "How sad:"
        echo "the file was locked."
        )

Thanks.

1 Answer 1

1

Since the parentheses there are part of the shell syntax, and not commands in their own right, you would have to do something like this:

flock -n lockfile.lock bash -c '( command list )'

Depending on what your exact set of commands are, the necessary quoting/escaping might be a slight additional challenge, but if that gets too hard, then just put your commands in a proper shell script, and call that instead of the bash -c ... syntax.

EDIT : In fact, using a shell this way, the parentheses are no longer necessary for command grouping (and in fact would be less efficient due to spawning an additional subshell), so this would suffice:

flock -n lockfile.lock bash -c 'command list'
Sign up to request clarification or add additional context in comments.

3 Comments

I don't know if the parentheses are needed. I was just creating an example of some character that will allow the script to separate the commands in different lines, instead of putting al the lines together between ;. I can prescind of parentheses or use any other character.
Well, the above would work even without parentheses (which aren't necessary), and would still give you the ability to run multiple commands under the lock - just flock -n lockfile.lock bash -c 'cmd1; cmd2; cmd3 ...'.
For readability, within a single quoted string, you can put as many newlines as required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.