Created
September 30, 2015 00:46
-
-
Save tamoyal/e622734595e2802ca4cc to your computer and use it in GitHub Desktop.
Script to sync a local directory to external hard drive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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