Skip to content

Instantly share code, notes, and snippets.

@justinmklam
Last active May 31, 2022 15:53
Show Gist options
  • Save justinmklam/add5a825bc5477e7d55814e434c8cf89 to your computer and use it in GitHub Desktop.
Save justinmklam/add5a825bc5477e7d55814e434c8cf89 to your computer and use it in GitHub Desktop.
Script to watch for changes in a directory and push files to a remote server. Add to /usr/local/bin for easy access (either directly or as a symlink from your home directory).
#!/usr/bin/env bash
"""Monitor a directory and rsync to a remote host on file change.
Example usage:
./rsync-watch.sh pi@raspberrypi.local . /home/pi/myproject
"""
RED=`tput setaf 1`
GREEN=`tput setaf 2`
YELLOW=`tput setaf 3`
CYAN=`tput setaf 6`
RESET=`tput sgr0`
EXCLUDE=(".git*" ".vscode" "*__pycache__/" "*.pyc" ".pytest_cache" ".coverage*" "*.egg-info/" ".sql")
# Parametrizee exclusions
exclude_opts=()
for item in "${EXCLUDE[@]}"; do
exclude_opts+=( --exclude="$item" )
done
run_rsync() {
rsync -avz $SOURCE_DIR $HOSTNAME:$REMOTE_DIR "${exclude_opts[@]}"
if [ $? -eq 0 ]; then
echo "${GREEN}Last sync: $(date)${RESET}"
else
echo "${RED}Error syncing: $(date)${RESET}"
fi
echo ""
}
HOSTNAME=$1
SOURCE_DIR=$2
REMOTE_DIR=$3
if [ -z "$1" ]; then
echo "Please enter a hostname (i.e. 'pi@raspberrypi.local')"
exit 1
elif [ -z "$2" ]; then
echo "Please enter a source directory (e.g. '.' for the current directory)"
exit 1
elif [ -z "$3" ]; then
echo "Please enter a remote directory (e.g. '/home/pi/myproject')"
exit 1
fi
echo "${YELLOW}Syncing source '$SOURCE_DIR' to remote '$REMOTE_DIR' at '$HOSTNAME'${RESET}"
run_rsync
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
while inotifywait -r -e modify,create,delete,move $SOURCE_DIR; do
run_rsync
done
elif [[ "$OSTYPE" == "darwin"* ]]; then
fswatch -o $SOURCE_DIR | while read f; do run_rsync; done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment