Skip to content

Instantly share code, notes, and snippets.

@tdb85
Last active July 17, 2018 23:31
Show Gist options
  • Save tdb85/03a67a1e6be5a1af39203617d8f4fb69 to your computer and use it in GitHub Desktop.
Save tdb85/03a67a1e6be5a1af39203617d8f4fb69 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
#
# DEPENDS ON: dialog, fswatch, rsync, ssh
#
# This script uses fswatch to monitor a directory for changes and when changes are detected
# Runs rsync to sync the changes to a remote server
#
# Features:
# - prompt for initial sync from remote server
# - delay after rsync to make sure it doesn't run too frequently
# - uses an SSH socket file to keep the connection open
#
LOCAL="$1"
REMOTE="$2"
# split REMOTE by comma into two vars
IFS=: read REMOTE_HOST REMOTE_DIR <<<"$REMOTE"
# check that vars above are set
[ -z "$LOCAL" ] && { echo "Missing LOCAL"; exit 1; }
[ -z "$REMOTE" ] && { echo "Missing REMOTE"; exit 1; }
# check if local is a directory
[ ! -d "$LOCAL" ] && { echo "LOCAL='$LOCAL' does not exist"; exit 1; }
[ -z "$REMOTE_DIR" ] && { echo "Missing REMOTE_DIR (please specify host:/path)"; exit 1; }
for CHECK_CMD in dialog rsync fswatch; do
if ! command -v $CHECK_CMD >/dev/null 2>&1; then
echo "Missing \"$CHECK_CMD\" command."
echo "You might be able to install with \"brew install $CHECK_CMD\""
exit 1
fi
done
MSG="$(printf "Perform initial remote to local sync?\nLOCAL=%s\nREMOTE=%s" "$LOCAL" "$REMOTE")"
SOCK="watch_dir_$$_$REMOTE_HOST.sock"
echo Using SSH socket file $SOCK
ssh -S $SOCK $REMOTE_HOST -M -f -N
ssh -S $SOCK $REMOTE_HOST -O check
if dialog --yesno "$MSG" 10 60; then
echo do local sync
rsync -rtli --delete -e "ssh -S $SOCK" "$REMOTE_HOST:$REMOTE_DIR/" "$LOCAL/"
fi;
echo "Listening for changes"
fswatch -r -o "$LOCAL" | while read c; do
echo "$c changes detected";
rsync -rtli --delete -e "ssh -S $SOCK" "$LOCAL/" "$REMOTE_HOST:$REMOTE_DIR/"
# delay before watching for changes again
sleep 3
echo "Sync done waiting for changes"
done;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment