bash script : rsync only if device mounted

 

The script checks if the location to backup the files to is a mountpoint. If not, the script should mount it or die. If it is a mountpoint, rsync should be run.

 

here goes

 

#!/bin/bash

##
## VARIABLES
##

# Set source location
BACKUP_FROM="/srv/media/"

# Set target location
BACKUP_TO="/media/backup/media/"
BACKUP_DEV="xxxxxxx-xxxxx-xxxxxxxxxxxxxxx" #UUID of the disk
BACKUP_MNT="/media/backup"

# Log file
LOG_FILE="/var/log/script_sync_media.log"

##
## SCRIPT
##

# Check that the log file exists
if [ ! -e "$LOG_FILE" ]; then
        touch "$LOG_FILE"
fi

# Check that source dir exists and is readable.
if [ ! -r  "$BACKUP_FROM" ]; then
        echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Unable to read source dir." >> "$LOG_FILE"
        echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Unable to sync." >> "$LOG_FILE"
        echo "" >> "$LOG_FILE"
        exit 1
fi

# Check that target dir exists and is writable.
if [ ! -w  "$BACKUP_TO" ]; then
        echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Unable to write to target dir." >> "$LOG_FILE"
        echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Unable to sync." >> "$LOG_FILE"
        echo "" >> "$LOG_FILE"
        exit 1
fi

# Check if the drive is mounted
if ! mountpoint "$BACKUP_MNT"; then
        echo "$(date "+%Y-%m-%d %k:%M:%S") - WARNING: Backup device needs mounting!" >> "$LOG_FILE"

        # If not, mount the drive
        if [ mount -U "$BACKUP_DEV" "$BACKUP_MNT" ]; then
                echo "$(date "+%Y-%m-%d %k:%M:%S") - Backup device mounted." >> "$LOG_FILE"
        else
                echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Unable to mount backup device." >> "$LOG_FILE"
                echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Unable to sync." >> "$LOG_FILE"
                echo "" >> "$LOG_FILE"
                exit 1
        fi
fi

# Start entry in the log
echo "$(date "+%Y-%m-%d %k:%M:%S") - Sync started." >> "$LOG_FILE"

# Start sync
if rsync -a -v --delete "$BACKUP_FROM" "$BACKUP_TO" &>> "$LOG_FILE"; then
        echo "$(date "+%Y-%m-%d %k:%M:%S") - Sync completed succesfully." >> "$LOG_FILE"
else
        echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: rsync-command failed." >> "$LOG_FILE"
	echo "$(date "+%Y-%m-%d %k:%M:%S") - ERROR: Unable to sync." >> "$LOG_FILE"
	echo "" >> "$LOG_FILE"
	exit 1
fi

# Unmount the drive so it does not accidentally get damaged or wiped
if [ umount "$BACKUP_MNT" ]; then
	echo "$(date "+%Y-%m-%d %k:%M:%S") - Backup device unmounted." >> "$LOG_FILE"
else
	echo "$(date "+%Y-%m-%d %k:%M:%S") - WARNING: Backup device could not be unmounted." >> "$LOG_FILE"
fi

# End entry in the log
echo "" >> "$LOG_FILE"
exit 0
It's only fair to share...Tweet about this on TwitterShare on Google+Share on FacebookShare on LinkedInEmail this to someone
Twitter Auto Publish Powered By : XYZScripts.com