SCP Directory Sync Script
Here's a bash script that will securely copy (SCP) a directory from one computer to another and keep them in sync. This script assumes you have SSH access between the two machines.
#!/bin/bash
# SCP Directory Sync Script
# Usage: ./sync_dir.sh [source_dir] [destination_host:destination_dir] [options]
# Check if required arguments are provided
if [ "$#" -lt 2 ]; then
echo "Usage: $0 [source_dir] [destination_host:destination_dir] [options]"
echo "Options:"
echo " -d, --dry-run Perform a trial run with no changes"
echo " -v, --verbose Enable verbose output"
echo " -r, --reverse Reverse the sync direction (destination -> source)"
exit 1
fi
# Parse arguments
SOURCE_DIR="$1"
DEST_PATH="$2"
DRY_RUN=false
VERBOSE=false
REVERSE=false
while [[ "$#" -gt 0 ]]; do
case $1 in
-d|--dry-run) DRY_RUN=true ;;
-v|--verbose) VERBOSE=true ;;
-r|--reverse) REVERSE=true ;;
*) echo "Unknown parameter passed: $1"; exit 1 ;;
esac
shift
done
# Extract destination host and path
IFS=":" read -r DEST_HOST DEST_DIR <<< "$DEST_PATH"
# Verify source directory exists
if [ ! -d "$SOURCE_DIR" ]; then
echo "Error: Source directory $SOURCE_DIR does not exist"
exit 1
fi
# Function to perform the sync
perform_sync() {
local src="$1"
local dest="$2"
local host="$3"
if [ "$VERBOSE" = true ]; then
echo "Syncing from $src to $host:$dest"
fi
if [ "$DRY_RUN" = true ]; then
echo "Dry run: Would execute: scp -r $src $host:$dest"
else
scp -r "$src" "$host:$dest"
if [ $? -ne 0 ]; then
echo "Error: SCP failed"
exit 1
fi
fi
}
# Perform the sync in the specified direction
if [ "$REVERSE" = true ]; then
# Reverse sync (destination -> source)
perform_sync "$DEST_HOST:$DEST_DIR" "$SOURCE_DIR" "localhost"
else
# Normal sync (source -> destination)
perform_sync "$SOURCE_DIR" "$DEST_DIR" "$DEST_HOST"
fi
echo "Sync completed successfully"
How to Use This Script
- Save the script as
sync_dir.sh
- Make it executable:
chmod +x sync_dir.sh
- Run it with the required parameters:
Basic Usage:
./sync_dir.sh /path/to/source_dir user@remote_host:/path/to/destination
Options:
-d, --dry-run: Perform a trial run without making changes
-v, --verbose: Show verbose output
-r, --reverse: Reverse the sync direction (destination -> source)
Example with options:
./sync_dir.sh /home/user/data user@192.168.1.100:/backup/data -v
Important Notes:
- You must have SSH access to the destination host with proper permissions
- The script uses SCP which is secure but may be slower than other methods for large directories
- For large directories, consider using
rsync over SSH instead of SCP
- The script doesn't handle deletions - it only copies new or modified files
- Make sure your SSH keys are set up for passwordless authentication if you want to run this unattended
Would you like me to modify this script to use rsync instead of scp for better performance with large directories?