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