Skip to content

Instantly share code, notes, and snippets.

@tamoyal tamoyal/sync_me
Created Sep 30, 2015

Embed
What would you like to do?
Script to sync a local directory to external hard drive
#!/usr/bin/env bash
# This will sync LOCAL_DIR directory to XTAL_DIR (which is my xtal hard drive)
# It's meant to run on frequent polling cron job so that it syncs "immediately"
# when the xtal is plugged in. It will do nothing if the xtal drive is not
# plugged in.
# After a successful sync, it will change the crontab so it is not sync'd again
# for 24 hours. This script assumes you don't need more frequent backing up than
# that because I use it for my projects directory where everything important is
# in a hosted git repo anyway. When it detects the hard drive to be disconnected
# by the failed "ls" command, it will then revert back to frequently polling.
# To start this process, just run "./sync_me -b" (b is for boot)
LOCAL_DIR=/Users/macbookair/Projects/
XTAL_DIR=/Volumes/LaCie/Projects
LOG_FILE=/tmp/cron.sync_me.log
COMMAND="$(pwd)/sync_me -x >> ${LOG_FILE} 2>&1"
SHORT_CRON="*/2 * * * * ${COMMAND}" # every 2 minutes
LONG_CRON="0 0 * * * ${COMMAND}" # every day at midnight
function write_cron {
local CRON_STRING="$1"
local CRON_FILE="$(pwd)/.sync_me.cron"
crontab -l > "$CRON_FILE"
echo "$CRON_STRING" > "$CRON_FILE"
crontab "$CRON_FILE"
rm "$CRON_FILE"
}
if [ "$1" == "-b" ]; then
write_cron "$SHORT_CRON"
exit
fi
if [ -d "$XTAL_DIR" ]; then
# External is pluggged in
if [ "$1" == "-x" ]; then
rsync -ra $LOCAL_DIR $XTAL_DIR
write_cron "$LONG_CRON"
else
# Dry run
rsync -ranv $LOCAL_DIR $XTAL_DIR
fi
else
# External is not plugged in, poll
write_cron "$SHORT_CRON"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.