Skip to content

Instantly share code, notes, and snippets.

@anselmobd
Last active August 12, 2022 00:10
Show Gist options
  • Save anselmobd/5130824008cc0ea19b83f81927b6eee6 to your computer and use it in GitHub Desktop.
Save anselmobd/5130824008cc0ea19b83f81927b6eee6 to your computer and use it in GitHub Desktop.
Avoid multiple instances of the script - Sample script [Linux] [Bash]
#!/usr/bin/env bash
# Avoid multiple instances of the script
# Sample script
# Based on description of
# man 1 flock
# Your code go inside of "main" function and other fuctions
function main {
echo $1 start
sleep $1
echo $1 end
}
# ----------------
script_file="$(/bin/readlink -f $0)"
lock_file=${script_file////_}
function already_executing_ {
echo "'${script_file}' already executing"
exit 1
}
(
flock -n 9 || already_executing_
main $@
) 9> /var/lock/${lock_file}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment