Last active
August 5, 2020 16:06
-
-
Save xandout/8d2419bc2ba8e0b98f4aff2665527a1c to your computer and use it in GitHub Desktop.
Mutex, Singleton, Only one instance of bash script running at a time
This file contains 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
#!/bin/bash | |
# Credit: https://unix.stackexchange.com/a/479309 | |
singleton(){ | |
# get absolute path to the script itself | |
script=`realpath $0` | |
# open bash script using file descriptor 6 | |
exec 6< "$script" | |
# lock file descriptor 6 OR show error message if script is already running | |
flock -n 6 || { echo "ERROR: script is already running" && exit 1; } | |
} | |
singleton | |
# Your code goes here | |
# Known limitations: | |
# Doesn't lock across users | |
# Doesn't lock if the script is copied to multiple places | |
echo "Running $@" | |
sleep 10 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment