How to determine if bash script is running from within the script
Often times when running a bash script, you don’t want it to be executed on a cron (again) if it’s already running. This little trick will show you how to code a contingency into your script so that it doesn’t doubly or triply execute while the first script instance is running.
Typically this involves using a temp or lock file, so that you can easily track the status of the script. I’m going to show you two examples.
Option #1: Use the
flock -n /var/run/your.lockfile -c /your/script
If done correctly, it will return immediately with a non 0 status if the script is already running.
Option #2: Code it into your script yourself
At the top of your script, put this:
if [[ -f /tmp/myscript.running ]] ; then exit fi touch /tmp/myscript.running
…and at the bottom of your script, put this (remove the temp file):
rm -f /tmp/myscript.running
Option #1 is going to be your first go-to, as it won’t have race condition or early exit problems. Happy scripting!