Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does flock understand && command for multiple bash commands?

Tags:

bash

flock

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.

like image 989
snh_nl Avatar asked Oct 27 '17 20:10

snh_nl


People also ask

What does the Bible say about knowing your flock?

Proverbs 27:23-27 -- Know well the condition of your flocks, and give attention to your herds, for riches do not last forever; and does a crown endure to all generations?

What is the full meaning of flock?

: a group of animals (such as birds or sheep) assembled or herded together. : a group under the guidance of a leader. especially : a church congregation.

What is flock used for?

Flock can be applied to glass, metal, plastic, paper or textiles. Flock design applications are also found on many items such as garments, greeting cards, trophies, promotional items, toys and book covers.

What is an example of flock?

A flock of birds, sheep, or goats is a group of them. They are gregarious birds and feed in flocks. You can refer to a group of people or things as a flock of them to emphasize that there are a lot of them.


1 Answers

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:

  • How to use flock and file descriptors to lock a file and write to the locked file?
like image 131
codeforester Avatar answered Oct 01 '22 09:10

codeforester