DEV Community

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

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

Benjamin Rancourt
A passionate Technology Analyst from Sherbrooke (Quebec) 🍁, who love almost everything about web development 🌐.
Originally published at benjaminrancourt.ca on ・1 min read

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? 😉

Discussion (0)