Run a Cron Bash Backup Script Safely
You might already be using the cron scheduler to run a daily bash script, perhaps you’re backing up files using rclone or rsync?
What happens if that script runs for more than 24 hours (or whatever time interval you’re using)? Bad things, as multiple instances of backup scripts can interfere with each other and corrupt data.
This bash one-liner stops a script running again if it’s already running elsewhere.
Prevent multiple instances of a bash script running
There are plenty of ways to solve this sort of race condition, but the simplest one I’ve found that works on most Linux based systems out-of-the-box is the PID file approach.
It’s a nice one-liner that you can prepend to the top of any bash script – whether it’s being called by cron or not – and it’ll make sure this named script is not already running before the rest of the file is executed.
#!/bin/bash
# Is this script already running? (https://benhoskins.dev/run-bash-once/)
pidof -o %PPID -x $0 >/dev/null && echo "ERROR: Script $0 already running" && exit 1
# do your script here...
Sources: I initially found a solution for preventing multiple instances of a rclone script running on the rclone forums discussing running rclone as a single instance , and after playing around with lockfile
and flock
I settled on using a simpler answer from the Unix Stack Overflow about making sure only once instance is running, I found a slightly nicer formatting via Benjamin Rancourt’s blog about the same subject.
Comments & Questions
Reply by email to send in your thoughts.
Comments may be featured here unless you say otherwise. You can encrypt emails with PGP too, learn more about my email replies here.
PGP: 9ba2c5570aec2933970053e7967775cb1020ef23