BASH
Sync Files for Deployment with `rsync`
Efficiently synchronize local development files to a remote server for deployment or backup, excluding sensitive files, using `rsync` in a Bash script.
#!/bin/bash
# Configuration variables
LOCAL_PATH="/path/to/your/local/project"
REMOTE_USER="your_ssh_user"
REMOTE_HOST="your_remote_server.com"
REMOTE_PATH="/var/www/your_app"
# Files/directories to exclude during synchronization
EXCLUDE_LIST=(
".git/"
"node_modules/"
"dist/" # If you build remotely
".env"
"config.local.php"
)
# Build the rsync exclude options
RSYNC_EXCLUDE_ARGS=""
for EXCL in "${EXCLUDE_LIST[@]}"; do
RSYNC_EXCLUDE_ARGS+="--exclude=$EXCL "
done
echo "Starting rsync synchronization from local to remote..."
echo "Source: $LOCAL_PATH"
echo "Destination: $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"
# Perform the rsync operation
# -a: archive mode (preserves permissions, timestamps, etc.)
# -v: verbose
# -z: compress file data during transfer
# --delete: delete extraneous files from dest (not in src)
# --progress: show progress during transfer
rsync -avz --delete --progress $RSYNC_EXCLUDE_ARGS "$LOCAL_PATH/" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH"
# Check the exit status of rsync
if [ $? -eq 0 ]; then
echo "
rsync synchronization completed successfully."
else
echo "
rsync synchronization failed. Check the error messages above."
exit 1
fi
How it works: This script leverages `rsync` for efficient file synchronization, often used for deploying web applications or updating remote development environments. It configures source and destination paths, along with a critical `EXCLUDE_LIST` to prevent unwanted files (like `.git` directories, `node_modules`, or sensitive `.env` files) from being transferred. The `rsync` command uses options for archive mode, compression, verbosity, and the `--delete` flag to ensure the remote directory precisely mirrors the local source, cleaning up old files.