Created
March 2, 2021 07:10
-
-
Save modest/ef2872ebefd5492889cceb395e82220a to your computer and use it in GitHub Desktop.
Two-way folder sync with rsync - Inefficient but portable
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 | |
remoteuser="$1" | |
remotehost="$2" | |
remotedir="$3" | |
localdir="$4" | |
syncstatusfile=".lastsync" | |
if [[ ! -d "$4" ]]; then | |
echo "Usage: | |
twowayrsync <remoteuser> <remotehost> '<remotedir>' '<localdir>' | |
" >&2 | |
exit 1 | |
fi | |
cd "${localdir}/" | |
if [[ -f "${localdir}/${syncstatusfile}" ]]; then | |
# Delete local files that have been deleted remotely since the last sync and haven't been updated locally | |
echo "Deleting locally:" | |
rsync --dry-run --out-format="${localdir}/%n" --recursive --ignore-existing --links --specials "${localdir}/" ${remoteuser}@${remotehost}:"${remotedir}/" | tr '\n' '\0' | xargs -0 -P 10 -I % find % -maxdepth 0 -not -newercc "${syncstatusfile}" -print -exec rm -rf {} \; | |
# Delete remote files that have been deleted locally since the last sync and haven't been updated remotely | |
echo "Deleting remotely:" | |
rsync --dry-run --out-format="${remotedir}/%n" --recursive --ignore-existing --links --specials ${remoteuser}@${remotehost}:"${remotedir}/" "${localdir}/" | tr '\n' '\0' | ssh ${remoteuser}@${remotehost} xargs -0 -P 10 -I % find % -maxdepth 0 -not -newercc "${remotedir}/${syncstatusfile}" -print -exec rm -rf {} \\\; | |
fi | |
# Update the sync time | |
touch "${syncstatusfile}" | |
# Add/update local files that are newer remotely | |
echo "Creating/updating locally:" | |
rsync --out-format="${localdir}/%n" --recursive --links --perms --times --specials --update --compress ${remoteuser}@${remotehost}:"${remotedir}/" "${localdir}/" | |
# Add/update remote files that are newer locally | |
echo "Creating/updating remotely:" | |
rsync --out-format="${remotedir}/%n" --recursive --links --perms --times --specials --update --compress "${localdir}/" ${remoteuser}@${remotehost}:"${remotedir}/" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment