Skip to content

Instantly share code, notes, and snippets.

@DavidePrincipi
Last active November 8, 2023 14:44
Show Gist options
  • Save DavidePrincipi/808b6ba9044b2f5b993c0a6b5b642eaa to your computer and use it in GitHub Desktop.
Save DavidePrincipi/808b6ba9044b2f5b993c0a6b5b642eaa to your computer and use it in GitHub Desktop.
Synchronize files remotely when changed locally (from a text editor)
#!/bin/bash
#
# Copyright (C) 2017 Davide Principi <davide.principi@nethesis.it>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Watch file changes under <src> and send them
# to the remote host+path <dst> with rsync
#
# general usage:
#
# isync <src> <dst>
#
# sample usage:
#
# touch ~/.isync.exclude
# isync root/usr/share/nethesis/ root@192.168.122.8:/usr/share/nethesis/ &
# isync root/etc/ root@192.168.122.8:/etc/ &
#
set -e
src=${1?missing src (local directory/file) argument}
dst=${2?missing dst (rsync location) argument}
echo "[NOTICE] running initial synchronization"
rsync -rli --exclude-from ~/.isync.exclude "${src}" "${dst}"
echo "[NOTICE] starting watches..."
inotifywait --format "%w%f" -m -q -e close_write --fromfile <(find "$src" -type d | grep -v -F -f <(cat ~/.isync.exclude | sed "s/^/\//")) | while read file; do
echo "[NOTICE] sync $(dirname "${dst}${file#${src}}") ... "
rsync -i "${file}" "${dst}${file#${src}}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment