Skip to content

Instantly share code, notes, and snippets.

@maurerle
Created October 13, 2024 17:00
Show Gist options
  • Save maurerle/d38c1f60fed1ad58abb4f4e5281f3a0b to your computer and use it in GitHub Desktop.
Save maurerle/d38c1f60fed1ad58abb4f4e5281f3a0b to your computer and use it in GitHub Desktop.
backup script which backs up a whole linux installation doing incremental backups using rsync
#!/bin/bash
# backup script which backs up a whole linux installation doing incremental backups using rsync
# Check for root priviliges
if [[ $EUID -ne 0 ]]; then
printf "Please run as root:\nsudo %s\n" "${0}"
exit 1
fi
set -o errexit
set -o nounset
set -o pipefail
readonly SCRIPT_PATH="${BASH_SOURCE:-$0}"
readonly ABS_SCRIPT_PATH=$(realpath "$SCRIPT_PATH")
readonly BACKUP_DIR="$(dirname "$ABS_SCRIPT_PATH")/$(hostname)"
readonly DATETIME="$(date '+%Y-%m-%d_%H:%M:%S')"
readonly BACKUP_PATH="${BACKUP_DIR}/${DATETIME}"
readonly LATEST_LINK="${BACKUP_DIR}/latest"
mkdir -p "${BACKUP_DIR}"
echo "backup from / to ${BACKUP_PATH}"
rsync -aAXv --delete \
--exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/usr/tmp/*","/run/*","/mnt/*","/media/*","/var/cache/*","/lost+found","/home/*/.cache/*"} \
--link-dest "${LATEST_LINK}" \
/* "${BACKUP_PATH}" > "backup_$(hostname)_log.txt" 2>&1
rm -rf "${LATEST_LINK}"
ln -s "${BACKUP_PATH}" "${LATEST_LINK}"
# delete older backups than the last 7
backup_count=$(find "${BACKUP_DIR}" -maxdepth 1 -type d | wc -l)
echo "found ${backup_count} backups"
if [ "$backup_count" -gt 8 ]; then # 8 because it includes the current backup and BACKUP_DIR itself
if [ -d "$BACKUP_DIR" ]; then
ls -dt "${BACKUP_DIR}"/*/ | tail -n +9 | xargs rm -rf
else
echo "Error: BACKUP_DIR is not set or is not a directory."
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment