Skip to content

Instantly share code, notes, and snippets.

@smsaladi
Last active February 1, 2018 19:42
Show Gist options
  • Save smsaladi/d44eeb4be0f412d1d3c3ca93414f32c8 to your computer and use it in GitHub Desktop.
Save smsaladi/d44eeb4be0f412d1d3c3ca93414f32c8 to your computer and use it in GitHub Desktop.
#!/bin/bash
# A simple wrapper script to avoid starting an rsync process
# if one is currently running
#
# Shyam Saladi (saladi@caltech.edu)
#
# parts from
# https://superuser.com/a/848123/470760
#
# set up in crontab (as follows polls ever 5 minutes; should roughly be size_of_file / bandwidth / 2)
# crontab -e
# */5 * * * * bash SCRIPT_DIR/rsync_with_lock.sh FROM_DIRECTORY TO_DIRECTORY >> /tmp/rsync_with_copy.txt 2>&1
LOCK_NAME="rsync_files"
LOCK_DIR='/tmp/'${LOCK_NAME}.lock
PID_FILE=${LOCK_DIR}'/'${LOCK_NAME}'.pid'
if mkdir ${LOCK_DIR} 2>/dev/null; then
# If the ${LOCK_DIR} doesn't exist, then start working & store the ${PID_FILE}
echo $$ > ${PID_FILE}
rsync --inplace $1 $2
rm -rf ${LOCK_DIR}
exit
else
if [ -f ${PID_FILE} ] && kill -0 $(cat ${PID_FILE}) 2>/dev/null; then
# Confirm that the process file exists & a process
# with that PID is truly running.
echo "Running [PID "$(cat ${PID_FILE})"]" >&2
exit
else
# If the process is not running, yet there is a PID file--like in the case
# of a crash or sudden reboot--then get rid of the ${LOCK_DIR}
rm -rf ${LOCK_DIR}
exit
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment