Skip to content

Instantly share code, notes, and snippets.

@jerieljan
Last active August 29, 2015 14:17
Show Gist options
  • Save jerieljan/5fd3153d6f5719b39470 to your computer and use it in GitHub Desktop.
Save jerieljan/5fd3153d6f5719b39470 to your computer and use it in GitHub Desktop.
A simple shell script that consistently observes a directory and synchronizes its contents when changes are found, using rsync's one-way sync.
#!/bin/sh
## A simple shell script that consistently observes a directory and synchronizes its contents when changes are found, using rsync's one-way sync.
## Most of the heavy lifting is really done by rsync, so what this script provides is just convenience over cron, notifications (if you have notify-pb) and rsync not being spammed by said cron job through a simple lockfile.
## simple-sync requires rsync, notify-pb (Pushbullet) and preferably run by a scheduler such as cron.
# Core variables
SYNC_HOME='/home/user'
SYNC_SOURCE='[email protected]:/path/to/source/*'
SYNC_DESTINATION="${SYNC_HOME}/path/to/destination/"
# Logging and notifications
SYNC_LOGTAG='simple-sync'
SYNC_LABEL_SOURCE='remote-machine'
SYNC_LABEL_DESTINATION='local-machine'
SYNC_TITLE="Synchronized files from ${SYNC_LABEL_SOURCE} to ${SYNC_LABEL_DESTINATION}"
SYNC_MESSAGE="New files were downloaded from ${SYNC_LABEL_SOURCE}"
# Only synchronize when the lock isn't present.
if [ ! -f "${SYNC_HOME}/.lock-sync" ]; then
touch "${SYNC_HOME}/.lock-sync"
# Begin syncing process. Log progress to /var/log/syslog for each step.
logger -t ${SYNC_LOGTAG} "Downloading files from ${SYNC_LABEL_SOURCE}"
if [ -n "$(\rsync -ai ${SYNC_SOURCE} ${SYNC_DESTINATION})" ]; then
# If rsync -i has STDOUT results, new files were then updated so it's safe to notify via Pushbullet.
notify-pb "${SYNC_TITLE}" "${SYNC_MESSAGE}"
logger -t ${SYNC_LOGTAG} "${SYNC_MESSAGE}"
else
# Else, there weren't any changes.
logger -t ${SYNC_LOGTAG} "No new files found."
fi
rm "${SYNC_HOME}/.lock-sync"
else
echo 'Process is already running. Try again later.'
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment