DEV Community

Cover image for How to ensure only one instance of a Bash script is running 🏃
Benjamin Rancourt
Benjamin Rancourt

Posted on • Originally published at benjaminrancourt.ca on

How to ensure only one instance of a Bash script is running 🏃

At work, we have an cron job in Bash which can sometimes take a long time to run, depending on some external conditions. So, it was therefore possible that 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
Enter fullscreen mode Exit fullscreen mode
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? 😉

Top comments (0)