Search code examples
bashpidlockfile

backup script requires a pid lock to prevent multiple instances


i have a bash script that runs daily rsync incremental backups.

my problem is i end up with multipul instances running. im new to bash scripts so im not sure if i have an issue in my script? posted below.

but i have read about a pid lockfile?

could anyone show me how i would go about adding this into my script?

#!/bin/bash
PATH=/usr/lib64/qt-     3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin


LinkDest=/home/backup/files/backupdaily/monday

WeekDay=$(date +%A |tr [A-Z] [a-z])

echo "$WeekDay"

case $WeekDay in

    monday) 
    echo "Starting monday's backup"
    rsync -avz --delete --exclude backup --exclude virtual_machines /home  /home/backup/files/backupdaily/monday --log- file=/usr/local/src/backup/logs/backup_daily.log
        ;;

    tuesday|wednesday|thursday|friday|saturday)
    echo "Starting inc backup : $WeekDay"   
    rsync -avz --exclude backup --exclude virtual_machines --link-dest=$LinkDest /home     /home/backup/files/backupdaily/$WeekDay --log- file=/usr/local/src/backup/logs/backup_daily.log
        ;;

    sunday)    exit 0
        ;;
esac

so it looks like this?

#!/bin/bash
PATH=/usr/lib64/qt-    3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin

trap "rm -f /tmp/backup_daily_lockfile && exit" SIGINT SIGTERM #Put this on the top to   handle CTRL+C or SIGTERM

test -f /tmp/backup_daily_lockfile && exit #before rsync to ensure that the script will   not run if there is another one running

LinkDest=/home/backup/files/backupdaily/monday

WeekDay=$(date +%A |tr [A-Z] [a-z])

echo "$WeekDay"
touch /tmp/backup_daily_lockfile #Before the rsync
case $WeekDay in

monday) 
echo "Starting monday's backup"
rsync -avz --delete --exclude backup --exclude virtual_machines /home /home/backup/files/backupdaily/monday --log-file=/usr/local/src/backup/logs/backup_daily.log
    ;;

tuesday|wednesday|thursday|friday|saturday)
echo "Starting inc backup : $WeekDay"   
rsync -avz --exclude backup --exclude virtual_machines --link-dest=$LinkDest /home /home/backup/files/backupdaily/$WeekDay --log-file=/usr/local/src/backup/logs/backup_daily.log
        ;;

    sunday)    exit 0
        ;;

rm -f /tmp/backup_daily_lockfile #After the rsync

esac

Solution

  • Add the following to your script:

    trap "rm -f /tmp/lockfile && exit" SIGINT SIGTERM #Put this on the top to handle CTRL+C or SIGTERM
    test -f /tmp/lockfile && exit #Before rsync to ensure that the script will not run if there is another one running
    
    touch /tmp/lockfile #Before the rsync
    
    rm -f /tmp/lockfile #After the rsync
    

    rename the lock file path/name according to your needs, you can also name it with the current PID using $$ variable.