Views:
145,497
Votes: 2
Tags:
bash
shell
process
lockfile
Link:
🔍 See Original Answer on Stack Overflow ⧉ 🔗
URL:
https://stackoverflow.com/q/49338826
Title:
Quick-and-dirty way to ensure only one instance of a shell script is running at a time
ID:
/2018/03/17/Quick-and-dirty-way-to-ensure-only-one-instance-of-a-shell-script-is-running-at-a-time
Created:
March 17, 2018
Upload:
September 15, 2024
Layout: post
TOC:
false
Navigation: false
Copy to clipboard: false
This one line answer comes from someone related Ask Ubuntu Q&A:
[ "${FLOCKER}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0" "$@" || :
# This is useful boilerplate code for shell scripts. Put it at the top of
# the shell script you want to lock and it'll automatically lock itself on
# the first run. If the env var $FLOCKER is not set to the shell script
# that is being run, then execute flock and grab an exclusive non-blocking
# lock (using the script itself as the lock file) before re-execing itself
# with the right arguments. It also sets the FLOCKER env var to the right
# value so it doesn't run again.