BASH
Efficient Local Directory Synchronization with rsync
Master the rsync command for fast and efficient local directory synchronization, perfect for deploying build artifacts to a web server's document root or local backups.
#!/bin/bash
# Source directory (e.g., your build output)
SOURCE_DIR="./dist/"
# Destination directory (e.g., your local web server's document root or a backup location)
DEST_DIR="/var/www/html/my-app/"
# --- Configuration End ---
# Ensure source directory exists
if [ ! -d "$SOURCE_DIR" ]; then
echo "Error: Source directory '$SOURCE_DIR' does not exist. Aborting."
exit 1
fi
# Ensure destination directory exists, or attempt to create it
if [ ! -d "$DEST_DIR" ]; then
echo "Destination directory '$DEST_DIR' does not exist. Attempting to create..."
mkdir -p "$DEST_DIR"
if [ $? -ne 0 ]; then
echo "Error: Failed to create destination directory '$DEST_DIR'. Check permissions."
exit 1
fi
fi
echo "Synchronizing files from '$SOURCE_DIR' to '$DEST_DIR' ..."
# rsync command for synchronization:
# -a, --archive: archive mode; equals -rlptgoD (no -H,-A,-X)
# -v, --verbose: increase verbosity
# -z, --compress: compress file data during the transfer
# --delete: delete extraneous files from destination dirs (not in source)
# --exclude: exclude specific files/patterns (e.g., node_modules, .git)
# --progress: show progress during transfer
# --dry-run: perform a trial run with no changes made (useful for testing)
# Example with --dry-run for testing:
# rsync -avz --delete --dry-run "$SOURCE_DIR" "$DEST_DIR"
rsync -avz --delete \
--exclude='node_modules/' \
--exclude='.git/' \
--exclude='.env' \
"$SOURCE_DIR" "$DEST_DIR"
# Check the exit status of rsync
if [ $? -eq 0 ]; then
echo "
Synchronization successful!"
else
echo "
Synchronization failed with errors. Please check the output above."
exit 1
fi
exit 0
How it works: This bash script demonstrates how to use the `rsync` command for efficient local directory synchronization, a common task for web developers. It's ideal for deploying static site builds, frontend applications, or assets from a build directory to a local web server's document root. The script uses `rsync` with the `-avz --delete` flags to achieve archival synchronization, verbose output, compression, and removal of files in the destination that no longer exist in the source. It also includes example `--exclude` patterns to prevent unwanted files (like `node_modules` or `.git`) from being copied, ensuring a clean and optimized deployment.