Categories

# Synchronizing live edits with fswatch

Synchronize development of a local project to a remote destination as you progress with your work.

fswatch is a great way to monitor for local file system changes, and then act upon them. This is similar to my “FMDMS” utility that I had made a while back.

Use case:
I develop locally, but sometimes I want to see those changes on a remote test server as I work. I keep a sync.bash script in each project that I want to test on a remote server. When I’m ready, I execute sync.bash locally.

Example:
In prior articles, I made extensive use of Docker for local development and remote deployment. When I’m working on a project that will run via Docker Compose, I place everything inside of /srv/ on the remote side, and can expect to see the same results on a remote system that I do on my development machine. From there, I can extend Docker Compose with multiple files (includes have been registered as a GitHub issue), and to differentiate between my Development and Production environments.

You could also add --delete-excluded as an argument to rsync, but when I’m working with systems where a database might exist in both locations, I want to exclude the file(s), but not delete them on the remote side.

#!/usr/bin/env bash

shopt -s expand_aliases

# Determine core paths
################################################################################
SOURCE="${BASH_SOURCE[0]}" # Dave Dopson, Thank You! - http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink SCRIPTPATH="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$SCRIPTPATH/$SOURCE" # if$SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
################################################################################
SCRIPTPATH="$( cd -P "$( dirname "$SOURCE" )" && pwd )" SCRIPTNAME=basename "$SOURCE"
################################################################################

fsSrc="${SCRIPTPATH}/" fsDest='USER@SERVER:~/srv/' alias run_rsync="rsync \ --progress \ --partial \ --archive \ --verbose \ --compress \ --delete \ --keep-dirlinks \ --rsh=/usr/bin/ssh \ \ --exclude 'sync.bash' \ --exclude '.*/' \ --exclude '.*' \ --exclude 'tmp/' \ --exclude 'ignore/' \ \ '${fsSrc}' \
'${fsDest}' \ " # Thanks: https://stackoverflow.com/questions/34575374/how-to-use-fswatch-and-rsync-to-automatically-sync-directories run_rsync; fswatch \ --print0 \ --one-per-batch \ --recursive \ "${fsSrc}" | while read -d "" event; do run_rsync; done


Did this article save you time or money? I'd love a coffee!

Did you find this useful?
Please share with those who you believe would find this useful too!