snh_nl
snh_nl

Reputation: 2955

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.

Upvotes: 7

Views: 1911

Answers (2)

Pankaj Tanwar
Pankaj Tanwar

Reputation: 1060

I had to do this in crontab. Here is my way -

*/30 * * * * cd /home/myfolder/ /usr/bin/flock -w 0 /home/myfolder/my-file.lock && python my_script.py > /dev/null 2>&1

Upvotes: 0

codeforester
codeforester

Reputation: 43039

Shell interprets your command this way:

flock -n ~/.my.lock cd /to/my/dir && python3.6 runcommand.py > /dev/null 2>&1
  • Step 1: Run flock -n ~/.my.lock cd /to/my/dir part
  • Step 2: If the command in step 1 exits with non-zero, skip step 3
  • Step 3: Run python3.6 runcommand.py > /dev/null 2>&1 part

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:

Upvotes: 1

Related Questions