Skip to content

Instantly share code, notes, and snippets.

@xandout
Last active August 5, 2020 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xandout/8d2419bc2ba8e0b98f4aff2665527a1c to your computer and use it in GitHub Desktop.
Save xandout/8d2419bc2ba8e0b98f4aff2665527a1c to your computer and use it in GitHub Desktop.
Mutex, Singleton, Only one instance of bash script running at a time
#!/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