Question

Here is my bash code:

(
flock -n -e 200 || (echo "This script is currently being run" && exit 1)
    sleep 10

    ...Call some functions which is written in another script...

    sleep 5

) 200>/tmp/blah.lockfile

I'm running the script from two shells successively and as long as the first one is at "sleep 5" all goes good, meaning that the other one doesn't start. But when the first turns to perform the code from another script (other file) the second run starts to execute.

So I have two questions here:

  1. What should I do to prevent this script and all its "children" from run while the script OR its "child" is still running. (I didn't find a more appropriate expression for running another script other than a "child", sorry for that :) ).

  2. According to man page, -n causes the process to exit when it fails to gain the lock, but as far as I can see it just wait until it can run. What am I missing ?

Was it helpful?

Solution

Your problem may be fairly mundane. Namely,

false || ( exit 1 )

Does not cause the script to exit. Rather, the exit instructs the subshell to exit. So change your first line to:

flock -n -e 200 || { echo "This script is currently being run"; exit 1; } >&2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top