I have two shell scripts that may be run in parallel but may also be run one at a time. Both scripts rely on an initial setup step that takes a while and can't be run by both at the same time.
To allow for parallel execution for the remainder, I've wrapped the setup step in control flow using flock
based on this recommendation.
This seems to work fine, but I'm not sure if the if-else construct is fully safe. Are there any hidden issues here that I'm missing?
set -euxo pipefail
(
# Only run setup if we're the first to acquire the lock
if flock -x -n 200 ; then
# Time-consuming setup that can't be run in parallel
else
# Wait for the lock to be released and then continue, timeout on 600s
flock -x -w 600 200;
fi
) 200>/tmp/setup.lock
Rest of the script that relies on setup being done
bash
, right? "Redirections using file descriptors greater than 9 should be used with care, as they may conflict with file descriptors the shell uses internally." – Kusalananda May 17 '21 at 12:23flock
invocation did what you mention in comment that should be OK, however, what is200>
use for ? is it a bad copy/paste ? – Archemar May 17 '21 at 12:23flock
. – Kusalananda May 17 '21 at 12:25