BASH
Synchronize Directories with Rsync
A flexible Bash script for efficient one-way synchronization of files and directories using `rsync`, perfect for deployment of static assets, local backups, or asset management.
#!/bin/bash
# This script uses rsync to synchronize files and directories.
# It performs a one-way sync from SOURCE to DESTINATION.
SOURCE_DIR="./source_files/" # Make sure this directory exists with some files
DESTINATION_DIR="./destination_backup/" # Make sure this directory exists or rsync will create it
# Create dummy directories and files for demonstration if they don't exist
if [ ! -d "$SOURCE_DIR" ]; then
mkdir -p "$SOURCE_DIR"
echo "Hello from source 1" > "$SOURCE_DIR/file1.txt"
echo "Hello from source 2" > "$SOURCE_DIR/file2.txt"
mkdir -p "$SOURCE_DIR/subfolder"
echo "Subfile content" > "$SOURCE_DIR/subfolder/subfile.txt"
echo "Dummy source files created."
fi
if [ ! -d "$DESTINATION_DIR" ]; then
mkdir -p "$DESTINATION_DIR"
echo "Dummy destination directory created."
fi
# Rsync options:
# -a: archive mode (recursively, preserve symlinks, permissions, ownership, timestamps)
# -v: verbose output
# --delete: delete extraneous files from dest dir (not in source dir)
# --exclude: exclude specific files or directories (can be used multiple times)
echo "
Starting synchronization from '$SOURCE_DIR' to '$DESTINATION_DIR' ..."
rsync -av --delete "$SOURCE_DIR" "$DESTINATION_DIR"
if [ $? -eq 0 ]; then
echo "
Synchronization successful!"
else
echo "
Synchronization failed. Please check the output for errors."
exit 1
fi
echo "
Contents of destination directory:"
ls -RF "$DESTINATION_DIR"
exit 0
How it works: This Bash script demonstrates how to effectively synchronize directories using `rsync`, a powerful utility for transferring and synchronizing files across local and remote systems. The script is configured for one-way synchronization from a `SOURCE_DIR` to a `DESTINATION_DIR`. It uses the `-av` flags for archive mode (which preserves permissions, ownership, timestamps, and is recursive) and verbose output. The crucial `--delete` flag ensures that any files in the destination that no longer exist in the source are removed, making the destination an exact mirror of the source. This is incredibly useful for deploying static website assets, managing development environments, or creating efficient incremental backups.