Skip to content

Instantly share code, notes, and snippets.

@magicstone1412
Created December 12, 2024 23:03
Show Gist options
  • Save magicstone1412/2569540eac95375c45d803dd182bae50 to your computer and use it in GitHub Desktop.
Save magicstone1412/2569540eac95375c45d803dd182bae50 to your computer and use it in GitHub Desktop.
Borg Backup Script
#!/bin/bash
# Exit immediately if a command exits with a non-zero status
set -e
# Variables (Customize these)
BACKUP_REPO="/path/to/backup/repo" # Borg repository location
BACKUP_SOURCE="/path/to/backup/source" # Directory to back up
PASSPHRASE="your-borg-passphrase" # Borg passphrase (avoid exposing in scripts; use environment variables instead)
BACKUP_LOG="/var/log/borg_backup.log" # Log file location
PRUNE_OPTIONS="--keep-daily=7 --keep-weekly=4 --keep-monthly=6" # Prune policy
# Export passphrase for Borg
export BORG_PASSPHRASE="$PASSPHRASE"
# Timestamp for backup archive
TIMESTAMP=$(date +"%Y-%m-%d_%H-%M-%S")
ARCHIVE_NAME="backup-$TIMESTAMP"
# Function to log messages
echo_log() {
echo "[$(date +"%Y-%m-%d %H:%M:%S")] $1" | tee -a "$BACKUP_LOG"
}
# Check if Borg repository exists
if ! borg list "$BACKUP_REPO" &>/dev/null; then
echo_log "Initializing new Borg repository at $BACKUP_REPO"
borg init --encryption=repokey "$BACKUP_REPO"
fi
# Create a backup
echo_log "Starting backup: $ARCHIVE_NAME"
borg create --stats --progress \
"$BACKUP_REPO::$ARCHIVE_NAME" \
"$BACKUP_SOURCE" \
2>> "$BACKUP_LOG"
echo_log "Backup completed: $ARCHIVE_NAME"
# Prune old backups
echo_log "Pruning old backups"
borg prune --list "$BACKUP_REPO" $PRUNE_OPTIONS 2>> "$BACKUP_LOG"
echo_log "Prune completed"
# Check repository integrity (optional, but recommended)
echo_log "Checking repository integrity"
borg check "$BACKUP_REPO" 2>> "$BACKUP_LOG"
echo_log "Repository integrity check completed"
# Unset passphrase for security
unset BORG_PASSPHRASE
# Done
echo_log "Backup process completed successfully"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment