Skip to content

Instantly share code, notes, and snippets.

@mcxiaoke
Forked from ryankurte/backup.env
Created November 20, 2022 12:02
Show Gist options
  • Save mcxiaoke/bca0e5ed7b4fa83a5ebc329deba68abf to your computer and use it in GitHub Desktop.
Save mcxiaoke/bca0e5ed7b4fa83a5ebc329deba68abf to your computer and use it in GitHub Desktop.
Linux backup automation
# Systemd unit for backup.sh service
# Place in /etc/systemd/system/backup.service
[Unit]
Description=Daily backup service
[Service]
Type=oneshot
User=root
ExecStart=/usr/bin/nice -n 19 /usr/bin/ionice -c2 -n7 /usr/sbin/backup.sh
RemainAfterExit=true
[Install]
WantedBy=multi-user.target
#!/bin/bash
# Local backup script, adapted from https://webworxshop.com/centralised-backups-with-restic-and-rsync/
# Place in /usr/sbin/backup.sh
# Enable with `sudo systemctl enable backup.timer`
# View status with `sudo systemctl list-timers --all` and `sudo systemctl status backup.service`
set -e
# Backup file destination
BACKUP_DEST=/media/large1/backups
# rsync excludes
EXCLUDES="--exclude=.cargo/registry --exclude=.toolchains --exclude=target --exclude=go/pkg --exclude=go/src --exclude=.cache --exclude=.mozilla"
# Set restic globals
export RESTIC_REPOSITORY=$BACKUP_DEST/restic
export RESTIC_PASSWORD_FILE=/root/.restic.pass
function do_rsync() {
# Write start info to log file
echo "Starting rsync backup job $1 to $BACKUP_DEST/raw$1 at $(date '+%Y-%m-%d %H:%M:%S')..."
# Ensure backup directory exists
mkdir -p $BACKUP_DEST/raw$1
# Execute rsync
/usr/bin/rsync -aP --delete $EXCLUDES $1 $BACKUP_DEST/raw
# Write end-info to log file
echo "Rsync job finished at $(date '+%Y-%m-%d %H:%M:%S')."
echo "Done"
}
echo "Starting rsync clone"
# rsync home directories
do_rsync /home
# rsync configuration
do_rsync /etc
# copy apt list
dpkg --get-selections > $BACKUP_DEST/packages.list
echo "Starting restic backup"
# Check database
restic check
# Execute backups
restic backup $BACKUP_DEST/raw/home
restic backup $BACKUP_DEST/raw/etc
# Clean up old snapshots
restic forget -d 7 -w 4 -m 6 -y 2
# Re-check the database
restic check
# Systemd timer for backup.sh service
# Place in /etc/systemd/system/backup.timer
[Unit]
Description=Daily backup service
[Timer]
OnCalendar=*-*-* 4:00:00
[Install]
WantedBy=timers.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment