#!/bin/bash #set -x # # The script: # • creates a new folder for each backup. The folder is named with the current date and time # • does an incremental backup # ⁃ each new run backs up the files that change # ⁃ the excluded items are listed in "exclude_from_list.txt" file # # The USB stick is formatted for “ext4”. # # # To do list: # - Add a check for a near full USB stick # # Check if run as root if [ $(id -u) -ne 0 ]; then printf "Script must be run as root. Try 'sudo script.sh'\n" exit 1 fi LOCK=/tmp/backupemonpilock if [ -f $LOCK ]; then echo;echo "emonPi backup job is running! Quitting this emonPi Log backup job.";echo exit 1 fi # get current date in "YYYY-MM-DD_HH.MM.SS" format - used to timestamp backup folders NOW=$(date "+%Y-%m-%d_%H.%M.%S") echo;echo "emonPi Log Backup - started on $NOW" # check for mounted USB and mount if needed mountpoint -q /mnt/usb || mount -vt ext4 /dev/sda1 /mnt/usb || exit; # Backup Source SOURCE="/var/log/" # SOURCE path MUST end with a "/" echo;echo "SOURCE = $SOURCE" # set path to backups BACKUPS="/mnt/usb/emonPi_Backups" if [ ! -d "$BACKUPS" ]; then rpi-rw # needed for emonPi mkdir -v "$BACKUPS" || (rpi-ro && exit); rpi-ro # needed for emonPi fi # set Backup Destination with timestamp DESTINATION="$BACKUPS/$NOW" echo "DESTINATION = $DESTINATION" mkdir -v -m 775 "$DESTINATION" || exit; chown -v pi:root "$DESTINATION" || exit; # set path for FLAG file (this FLAG file is the last backup) FLAGFILE="${BACKUPS}/emonpi_log_flag.txt" #echo "FLAGFILE = $FLAGFILE" if [ -f "$FLAGFILE" ]; # does the FLAG file exist? then echo;echo "File $FLAGFILE exists" FLAGFILECONTENTS="$(<"$FLAGFILE")" echo "Last Backup on = $FLAGFILECONTENTS" LinkDest="--link-dest=../$FLAGFILECONTENTS" fi # rsync Flags: # --archive archive mode - preserves all file attributes and permissions # --hard-links preserve hard links # --stats file-transfer stats # --link-dest hardlink to files in DIR when unchanged. # --out-format output updates using specific format # --recursive recurse into directories # --chown simple username/groupname mapping =youruser:yourgroup echo;echo;echo -e "\033[1mRun RSYNC - copy log files from /var/log\033[0m";echo #echo;echo;echo "Run RSYNC - copy log files from /var/log";echo rsync --archive --hard-links --stats ${LinkDest} \ --chown=pi:pi \ --out-format="%t %i %f %b" \ "/var/log/" "${DESTINATION}/" || exit; echo;echo "Run RSYNC - copy log files from /home/pi/data";echo rsync --archive --hard-links --stats ${LinkDest} \ --chown=pi:pi \ --out-format="%t %i %f %b" \ --include="*.log" --exclude "*" \ "/home/pi/data/" "${DESTINATION}" || exit; # Set FLAG for this backup. Used for next backup echo "${NOW}" > "${FLAGFILE}" echo;echo "emonPi Log Backup - completed at $(date "+%Y-%m-%d_%H.%M.%S")" # Done! exit