BASH
Automating Daily Incremental Backups with Rsync to Remote Server
Learn to create a robust Bash script for daily incremental backups of your web application files to a remote server using rsync, ensuring data safety and efficient transfers.
#!/bin/bash
# Configuration
SOURCE_DIR="/var/www/html/my_webapp"
DEST_HOST="[email protected]"
DEST_BASE_DIR="/backups/my_webapp"
# Create timestamped directory for full backup and current link for incremental reference
DATE_FORMAT="%Y-%m-%d_%H-%M-%S"
CURRENT_BACKUP_DIR="${DEST_BASE_DIR}/current"
SNAPSHOT_DIR="${DEST_BASE_DIR}/$(date +${DATE_FORMAT})"
mkdir -p "${SNAPSHOT_DIR}"
# Run rsync for incremental backup
# --archive (-a): archive mode; equals -rlptgoD (no -H,-A,-X)
# --compress (-z): compress file data during the transfer
# --delete: delete extraneous files from dest dirs (implies --recursive)
# --link-dest: hardlink files that are unchanged from the LAST_BACKUP_DIR
# --info=progress2: show progress during transfer
# --exclude: exclude specific files/directories (e.g., node_modules, .git, vendor)
rsync -az --delete \
--link-dest="${CURRENT_BACKUP_DIR}" \
--exclude='node_modules' \
--exclude='.git' \
--exclude='vendor' \
"${SOURCE_DIR}/" "${DEST_HOST}:${SNAPSHOT_DIR}/"
# Update the 'current' symlink to point to the latest backup
# -h: create a symbolic link
# -f: remove existing destination files
# -n: do not dereference symlinks
ssh "${DEST_HOST}" "ln -sfn ${SNAPSHOT_DIR} ${CURRENT_BACKUP_DIR}"
if [ $? -eq 0 ]; then
echo "Backup successful to ${DEST_HOST}:${SNAPSHOT_DIR}"
else
echo "Backup failed!"
# Optionally add email notification here
fi
How it works: This Bash script automates daily incremental backups of a web application's files to a remote server using `rsync` over SSH. It configures source and destination paths, then uses `rsync -az --delete --link-dest` to efficiently transfer only changed files, hardlinking unchanged files from the previous day's backup. This saves significant disk space and transfer time. After a successful transfer, it updates a 'current' symbolic link on the remote server to point to the latest backup, providing a consistent reference for the next incremental backup.