Skip to content

Instantly share code, notes, and snippets.

@blankhat1610
Last active January 6, 2025 08:29
Show Gist options
  • Save blankhat1610/9610b709144a96e9c8ae4bded238fc06 to your computer and use it in GitHub Desktop.
Save blankhat1610/9610b709144a96e9c8ae4bded238fc06 to your computer and use it in GitHub Desktop.
Sync local directory to remote directory using rsync
#!/bin/bash
# Function to display usage
usage() {
echo "USAGE: $0 <local_dir> <user@remote_ip> <remote_dir>"
echo "EXAMPLE: $0 . [email protected] /home/user/tools"
exit 1
}
# Check if help option is provided
if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
usage
fi
# Check if the number of arguments is not equal to 3
if [ "$#" -ne 3 ]; then
usage
fi
LOCAL_DIR=$1
REMOTE_HOST=$2
REMOTE_DIR=$3
# Ensure local directory has trailing slash for rsync
LOCAL_DIR="${LOCAL_DIR%/}/"
# Check if local directory exists
if [ ! -d "$LOCAL_DIR" ]; then
echo "ERROR: Local directory $LOCAL_DIR does not exist."
exit 1
fi
# Check if .git and .gitignore exist in the local directory
if [ ! -d "$LOCAL_DIR/.git" ]; then
echo "Warning: .git directory does not exist in $LOCAL_DIR"
fi
EXCLUDE_FROM_OPTION=""
if [ -f "$LOCAL_DIR/.gitignore" ]; then
EXCLUDE_FROM_OPTION="--exclude-from=$LOCAL_DIR/.gitignore"
else
echo "Warning: .gitignore file does not exist in $LOCAL_DIR"
fi
# Sync the local directory to the remote directory
echo "Syncing from $LOCAL_DIR to $REMOTE_HOST:$REMOTE_DIR"
rsync -avz --exclude '.git' --exclude '.DS_Store' $EXCLUDE_FROM_OPTION \
"$LOCAL_DIR" \
"$REMOTE_HOST:$REMOTE_DIR" \
--delete
if [ $? -eq 0 ]; then
echo "Sync completed successfully"
else
echo "Sync failed"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment