Advanced Backup and Restore with Automation & Systemd Integration

1. Borg: Automated Backup Script + systemd Timer

Create a backup script borg-backup.sh:

#!/bin/bash
REPO="/path/to/backup/repo"
SOURCE="/path/to/source"
EXCLUDES="--exclude '*.cache' --exclude '/tmp' --exclude-caches"

export BORG_PASSPHRASE="YourStrongPassphrase"

borg create --stats --progress --compression lz4 $EXCLUDES \
  $REPO::backup-$(date +%Y%m%d-%H%M%S) $SOURCE

borg prune -v --keep-daily=7 --keep-weekly=4 --keep-monthly=6 $REPO

Make it executable:

chmod +x borg-backup.sh

Create systemd service borg-backup.service:

[Unit]
Description=Borg Backup Service

[Service]
Type=oneshot
ExecStart=/path/to/borg-backup.sh

Create systemd timer borg-backup.timer to run daily at 2:30 AM:

[Unit]
Description=Run Borg Backup daily at 2:30 AM

[Timer]
OnCalendar=*-*-* 02:30:00
Persistent=true

[Install]
WantedBy=timers.target

Enable and start timer:

sudo systemctl enable borg-backup.timer
sudo systemctl start borg-backup.timer

2. Rsync: Incremental Backup Script with Exclude File & Cron

Example rsync-incremental.sh:

#!/bin/bash
SRC="/path/to/source/"
DEST="/path/to/backup/"
PREV_BACKUP="/path/to/previous/backup/"
EXCLUDE_FILE="/path/to/exclude-list.txt"

rsync -a --delete --exclude-from="$EXCLUDE_FILE" --link-dest="$PREV_BACKUP" \
  "$SRC" "$DEST"/backup-$(date +%Y%m%d-%H%M%S)/

Make executable:

chmod +x rsync-incremental.sh

Add cron job to run daily at 3:00 AM:

0 3 * * * /path/to/rsync-incremental.sh

3. Tar: Backup with Exclude & Rotating Archives Script + Cron

Script tar-backup.sh to create compressed backups and keep last 7 archives:

#!/bin/bash
SRC="/path/to/source"
BACKUP_DIR="/path/to/backups"
EXCLUDE_FILE="/path/to/exclude-list.txt"
DATE=$(date +%Y%m%d-%H%M%S)
ARCHIVE="$BACKUP_DIR/backup-$DATE.tar.gz"

tar czvf $ARCHIVE --exclude-from="$EXCLUDE_FILE" $SRC

# Keep only last 7 backups
ls -1tr $BACKUP_DIR/backup-*.tar.gz | head -n -7 | xargs -d '\n' rm -f --

Make executable and schedule with cron at 4:00 AM:

chmod +x tar-backup.sh

0 4 * * * /path/to/tar-backup.sh

4. Restic: Automated Backup with Prune and systemd

Script restic-backup.sh:

#!/bin/bash
export RESTIC_REPOSITORY="/path/to/restic/repo"
export RESTIC_PASSWORD="YourResticPassword"

restic backup /path/to/source \
  --exclude '*.cache' \
  --exclude '/tmp'

# Remove old snapshots but keep recent backups
restic forget --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune

Make executable:

chmod +x restic-backup.sh

systemd service restic-backup.service:

[Unit]
Description=Restic Backup Service

[Service]
Type=oneshot
ExecStart=/path/to/restic-backup.sh

systemd timer restic-backup.timer to run every day at 1:00 AM:

[Unit]
Description=Run Restic Backup daily at 1:00 AM

[Timer]
OnCalendar=*-*-* 01:00:00
Persistent=true

[Install]
WantedBy=timers.target

Enable and start timer:

sudo systemctl enable restic-backup.timer
sudo systemctl start restic-backup.timer

Additional Tips