Skip to content

Clean Up Script for Backups

Add a clean up script that will keep the last X restic backups.

Step 1 - Check current snapshot count

Run these commands on the server (example in apex) (replace your_password with the actual RESTIC password)

# temporary export for this shell
export RESTIC_PASSWORD='your_password'

sudo /usr/bin/restic snapshots -r /mnt/bottle/backup/restic/

some servers the binaries are located in /usr/local/sbin/restic

What you should see is a list of the snapshots and at the bottom the total snapshots.

Create the Clean Up Script

Create /usr/local/sbin/restic-cleanup.sh. This script locks files so two instances won't run at the same time. Pick a value for KEEP_LAST.

sudo tee /usr/local/sbin/restic-cleanup.sh > /dev/null <<'EOF'
#!/usr/bin/env bash
set -euo pipefail

LOCKFILE=/var/lock/restic-cleanup.lock
REPO="/mnt/bottle/backup/restic/"
RESTIC_BIN="/usr/bin/restic"
LOGFILE="/var/log/restic-cleanup.log"
KEEP_LAST=10   # <<-- change this to the desired X snapshots.

# Prefer password file method.
export RESTIC_PASSWORD='----'
# export RESTIC_PASSWORD_FILE="/etc/restic/backup.pw"

DRYRUN=${1:-false}
if [[ "$DRYRUN" == "dry-run" ]]; then
    DRY="--dry-run"
    echo "Running in dry-run mode — nothing will actually be deleted."
else
  DRY=""
fi

# Ensure PATH includes /usr/bin
export PATH="/usr/bin:$PATH"
umask 027


{
  echo "==== $(date -Iseconds) starting restic cleanup (keep last ${KEEP_LAST}) ===="
  # show current counts
  $RESTIC_BIN snapshots -r "$REPO" --json | jq '. | length' || true

  # Run forget/prune (either dry-run or real)
  echo "---- running restic forget --keep-last ${KEEP_LAST} ${DRY} ----"
  $RESTIC_BIN forget --keep-last "$KEEP_LAST" --prune $DRY -r "$REPO"

  echo "---- done; new snapshot count ----"
  $RESTIC_BIN snapshots -r "$REPO" --json | jq '. | length' || true
  echo "==== $(date -Iseconds) finished ===="
} 2>&1 | tee -a "$LOGFILE"
EOF

sudo chmod 750 /usr/local/sbin/restic-cleanup.sh
sudo chown root:root /usr/local/sbin/restic-cleanup.sh
sudo touch /var/log/restic-cleanup.log
sudo chown root:root /var/log/restic-cleanup.log
sudo chmod 640 /var/log/restic-cleanup.log

Make the script executable

sudo chmod +x /usr/local/sbin/restic-cleanup.sh

Execute the script

sudo /usr/local/sbin/restic-cleanup.sh dry-run

important argument to test things and not actually delete anything: dry-run

Check logs

sudo cat /var/log/restic-cleanup.log