How to Ensure Only One Instance of a Bash Script Is Running 🏃

A single line to make sure only one bash script instance is running, I don't think it could be any simpler! 😅

1 min read
How to Ensure Only One Instance of a Bash Script Is Running 🏃
Photo by Caique Araujo from Pexels

At work, we have a cron job in Bash which can sometimes take a long time to run, depending on some external conditions. So, it was, therefore, possible that the script would not be finished before its next execution. In our case, we really didn't want this to happen, as it could have corrupted some sensitive data if two instances were running at the same time... 🤢

So, one way to ensure that only one instance is running is to introduce the concept of a lock. Fortunately, it was much easier than we think to implement, thanks to a Stack Exchange answer by Sethu. 🥳

#!/bin/bash

# Check if another instance of this script is running
pidof -o %PPID -x $0 >/dev/null && echo "ERROR: Script $0 already running" && exit 1

# ... Rest of your script
Just add the pidof line at the top of your Bash script, and you'll be sure that only one instance of your script can be running at a time.

A powerful line, right? 😉