bashflock

Does flock understand && command for multiple bash commands?


I am using bash and flock on centos.

Normally I would run cd /to/my/dir && python3.6 runcommand.py

But then we add it to cron and don't want output so add > /dev/null 2>&1

And add a flock before it to prevent multiple instances, like so:

flock -n ~/.my.lock cd /to/my/dir && python3.6 runcommand.py > /dev/null 2>&1

Question Only does this flock the cd /to/my/dir and then execute the python3.6 (normally without flock) or does it flock the complete row of bash commands (so both) and only unlock when python3.6 runcommand.py is also finished?

Not clear from the man and examples I found.


Solution

  • Shell interprets your command this way:

    flock -n ~/.my.lock cd /to/my/dir && python3.6 runcommand.py > /dev/null 2>&1
    

    So, flock has no business with && or the right side of it.

    You could do this instead:

    touch ./.my.lock # no need for this step if the file is already there and there is a potential that some other process could lock it
    (
      flock -e 10
      cd /to/my/dir && python3.6 runcommand.py > /dev/null 2>&1
    ) 10< ./.my.lock
    

    See this post on Unix & Linux site: