Last active
September 6, 2020 21:11
-
-
Save jarrettgilliam/01fe1e22c3c6e22c9b03 to your computer and use it in GitHub Desktop.
Mondo archive backup script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Backup system with mondoarchive | |
backupLocation='' | |
nbrOfBackups=8 | |
ignore='/home|/media|/mnt|/dev|/var/lib/transmission-daemon' | |
backupPrefix="Backup." | |
function is_integer() { | |
echo "$1" | grep -qE '^[0-9]+$' | |
return "$?" | |
} | |
function print_script_usage_and_exit() { | |
if [ ! -z "$1" ]; then | |
echo -e "$1\n" >&2 | |
fi | |
echo "Usage: mondo-backup.sh -l '/path/to/backup' [-n 16]" >&2 | |
echo " -l : The backup location directory." >&2 | |
echo " -n : The number of backups to keep. Defaults to 16." >&2 | |
exit 1 | |
} | |
# parse arguments | |
while getopts :l:n: option; do | |
case "$option" in | |
l) backupLocation="$OPTARG" ;; | |
n) nbrOfBackups="$OPTARG" ;; | |
\?) print_script_usage_and_exit ;; | |
:) print_script_usage_and_exit "Error: Option '-$OPTARG' requires an argument" ;; | |
esac | |
done | |
shift $((OPTIND-1)) | |
# Validate input | |
if [ -z "$backupLocation" ]; then | |
print_script_usage_and_exit "Error: Backup location not specified" | |
elif [ ! -d "$backupLocation" ]; then | |
print_script_usage_and_exit "Error: Backup location '$backupLocation' doesn't exist" | |
elif ! is_integer "$nbrOfBackups"; then | |
print_script_usage_and_exit "Error: Number of backups must be an integer" | |
fi | |
# Build work variables | |
thisBackup="${backupLocation}"/"${backupPrefix}$(date +'%F.%T.%Z')" | |
# Mondo backup | |
mkdir "${thisBackup}" | |
/usr/sbin/mondoarchive -OVi9 -d "${thisBackup}" -E "${ignore}" >/dev/null 2>/dev/null | |
# Handle errors | |
rc="$?" | |
if [ "$rc" -ne 0 ]; then | |
echo -e "Error: Backup failed with error code $rc, deleting it.\n" >&2 | |
cat /var/log/mondoarchive.log >&2 | |
rm -rf "${thisBackup}" | |
exit "$rc" | |
fi | |
cp /var/log/mondoarchive.log "${thisBackup}" | |
# Delete old backups | |
IFS=$(echo -en "\n\b") | |
if [ $(ls -d "${backupLocation}"/"${backupPrefix}"* | wc -l) -gt "${nbrOfBackups}" ]; then | |
rm -rf $(ls -d "${backupLocation}"/"${backupPrefix}"* | sort | \ | |
head -n $(expr $(ls -d "${backupLocation}"/"${backupPrefix}"* | wc -l) - "${nbrOfBackups}")) | |
fi | |
unset IFS |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment