Skip to content

Instantly share code, notes, and snippets.

@paulera
Last active March 1, 2023 19:09
Show Gist options
  • Save paulera/d654aedcaad2c812a520156f10712124 to your computer and use it in GitHub Desktop.
Save paulera/d654aedcaad2c812a520156f10712124 to your computer and use it in GitHub Desktop.
rsync for backups and restore, preserving folders structure

Backup tricks with rsync

Creating backups

The commands below use a folder ~/backup/ as storage. Files are copied with the following features:

  • rsync --relative: Tree structure relative to / is preserved (subdirectories created if needed).
    • realpath --no-symlinks: Symlinks not resolved, so in case you use the backup to restore files, they will end up where they were found.
  • --recursive: Subfolders too
  • --perms: Permissions preserved
  • --copy-links: Don't backup links, but the files they are pointing to

Backup a file or folder (basic concept):

# Backup one file
rsync --perms --copy-links --relative $(realpath --no-symlinks file-to-backup) ~/backup/

# Backup a directory and all inside it
rsync --perms --copy-links --relative --recursive $(realpath --no-symlinks folder-to-backup) ~/backup/

# Backup the current directory
rsync --perms --copy-links --relative --recursive $(realpath --no-symlinks .) ~/backup/

Restoring backups

To restore a the backup, while saving a copy of whatever was replaced (just in case, because rsync doesn't do confirmations):

rsync --verbose --recursive --backup-dir=/tmp/backup-just-in-case ~/backup/ /
#!/bin/bash
BACKUP_LOCATION=~/backup
if [ ! -d "${BACKUP_LOCATION}" ]; then
mkdir -p ${BACKUP_LOCATION}
fi
if [ ! -d "$1" ] && [ ! -f "$1" ]; then
echo "Invalid folder/file $1"
exit 1
fi
rsync --perms --copy-links --relative --recursive $(realpath --no-symlinks $1) $(realpath ${BACKUP_LOCATION})/
#!/bin/bash
BACKUP_LOCATION=~/backup
TODAY=$(date +"%Y-%m-%d" | sed s/-//g)
NOW=$(date +"%T" | sed s/://g)
if [ ! -d "$1" ] && [ ! -f "$1" ]; then
echo "Invalid folder/file $1"
exit 1
fi
if [ ! -d "${BACKUP_LOCATION}" ]; then
echo "Can't find the backup location ${BACKUP_LOCATION}"
exit 1
fi
TORESTORE=$(realpath --relative-to=${BACKUP_LOCATION} $1)
cd ${BACKUP_LOCATION}
rsync --relative --recursive --backup-dir=/tmp/rsync_backup_${TODAY}_${NOW}/ ./${TORESTORE} /
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment