Created
November 4, 2024 02:25
-
-
Save MohamedElashri/d00c26c5b533236d06207e5141fab6ca to your computer and use it in GitHub Desktop.
script to sync between two machines via resync over ssh connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Define colors for logs | |
GREEN='\033[0;32m' | |
RED='\033[0;31m' | |
NC='\033[0m' # No color | |
log_info() { echo -e "${GREEN}[INFO]${NC} $1"; } | |
log_error() { echo -e "${RED}[ERROR]${NC} $1"; } | |
# Parse user inputs | |
REMOTE_USER="$1" | |
REMOTE_SERVER="$2" | |
REMOTE_PATH="$3" | |
LOCAL_PATH="$4" | |
SYNC_INTERVAL="${5:-10}" | |
# Validate local and remote paths | |
if [ ! -d "$LOCAL_PATH" ]; then | |
log_info "Local path '$LOCAL_PATH' does not exist. Creating it." | |
mkdir -p "$LOCAL_PATH" | |
fi | |
# Function to generate a checksum file list in a directory | |
generate_checksum() { | |
find "$1" -type f ! -path "*/node_modules/*" -exec md5sum {} + 2>/dev/null | sort | md5sum | awk '{print $1}' | |
} | |
# Sync function from local to remote | |
sync_local_to_remote() { | |
log_info "Syncing changes from local to remote" | |
rsync -avz --exclude 'node_modules' "$LOCAL_PATH/" "${REMOTE_USER}@${REMOTE_SERVER}:${REMOTE_PATH}" | |
} | |
# Sync function from remote to local | |
sync_remote_to_local() { | |
log_info "Syncing changes from remote to local" | |
rsync -avz --exclude 'node_modules' "${REMOTE_USER}@${REMOTE_SERVER}:${REMOTE_PATH}/" "$LOCAL_PATH" | |
} | |
# Monitor changes based on checksum comparison | |
while true; do | |
# Calculate local checksum | |
local_checksum=$(generate_checksum "$LOCAL_PATH") | |
# Retrieve and calculate remote checksum | |
remote_checksum=$(ssh "$REMOTE_USER@$REMOTE_SERVER" "cd $REMOTE_PATH && find . -type f ! -path '*/node_modules/*' -exec md5sum {} + 2>/dev/null | sort | md5sum | awk '{print \$1}'") | |
# Sync if checksums differ | |
if [ "$local_checksum" != "$remote_checksum" ]; then | |
log_info "Detected changes. Syncing..." | |
sync_remote_to_local | |
sync_local_to_remote | |
else | |
log_info "No changes detected. Skipping sync." | |
fi | |
# Wait before the next check | |
sleep "$SYNC_INTERVAL" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment