Last active
November 25, 2022 13:59
-
-
Save Thomashrb/b99e032d969dac7acb5c0f510c71098c to your computer and use it in GitHub Desktop.
Sequence 2 commands behind a lock
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Locking from: https://gist.github.com/jpclipffel/0b8f470be029fc9e3f07 | |
# Run two bash commands in sequence using flock to prevent | |
# from running multiple instances in paralell | |
# ./sequenced.sh -g echo 'Hello' > test.txt -t cat test.txt -n lock_name | |
while getopts 1:2:n: flag; do | |
case "${flag}" in | |
1) FIRST_CMD=${OPTARG} ;; | |
2) SECOND_CMD=${OPTARG} ;; | |
n) LOCK_FILE=${OPTARG} ;; | |
esac | |
done | |
function first(){ | |
eval "${FIRST_CMD}" | |
return 0 | |
} | |
function second(){ | |
eval "${SECOND_CMD}" | |
return 0 | |
} | |
# Lock timeout in seconds -- 86400 seconds == 1 day | |
TIMEOUT=86400 | |
# Create the lockfile. | |
touch $LOCK_FILE | |
# Create a file descriptor over the given lockfile. | |
exec {FD}<>$LOCK_FILE | |
# Try to lock the file descriptor $FD during $TIMEOUT seconds. | |
# If it failsm exit with an error. | |
# Otherwise, the lock is acquired and implicitely droped at the end of the script. | |
if ! flock -x -w $TIMEOUT $FD; then | |
echo "Failed to obtain a lock within $TIMEOUT seconds" | |
echo "Another instance of sequenced.sh is probably running against the same lock file." | |
exit 1 | |
else | |
echo "Lock acquired running sequenced commands" | |
first && second | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment