2 cron rsync
Lucas Frérot edited this page 2024-12-26 13:40:14 +01:00

Backups with cron and rsync

Here is a sample script for incremental backups with rsync. It uses physical links to avoid data duplication.

#!/usr/bin/env bash

set -euo pipefail

if [ $# -ne 2 ]; then
    echo "usage: $0 source destination"
    exit 1
fi

SRCDIR=$(realpath $1)
BACKUPDIR=$(realpath $2)
CURRENTDIR="$BACKUPDIR/current"

POSTFIX=$(date --iso-8601=seconds)
CURRENT_BCKP="$BACKUPDIR/$POSTFIX/"

# Backup data with physical links
rsync -Aax --info=STATS1 --delete --link-dest="$CURRENTDIR" "$SRCDIR" "$CURRENT_BCKP"

# Create "current" symbolic link to latest backup
ln -fns $(basename "$CURRENT_BCKP") "$CURRENTDIR"

One can use cron to execute a daily backup to an external drive. To add a new scheduled task, use crontab -e and something like:

0 12 * * * /path/to/backup.sh $HOME /mnt/drive/path/to/backupdir

This will run the backup task every day at noon.