Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Synchronize directories between computers using rsync (and SSH)
#!/usr/bin/env ruby -rubygems
# INSTALLATION:
# Save this script as something like `sync-to` somewhere in $PATH.
# Link it to `sync-from` in the same location. (i.e. `ln sync-to sync-from`)
require 'shellwords'
PROGRAM_NAME = File.basename($PROGRAM_NAME)
RSYNC = 'rsync'
RSYNC_BASIC_OPTIONS = '--rsh="ssh" --partial --progress --archive --human-readable'
RSYNC_EXCLUDE_PATTERNS = %w{.DS_Store .localized}
#
# helpers
#
def print_usage_and_die()
puts <<-END.gsub(/^ {4}/, '')
Synchronize directories between computers using rsync (and SSH).
Usage: #{PROGRAM_NAME} HOST DIR [options]
HOST any host you'd use with SSH
DIR must be available on both the local and the remote machine
Options:
You can pass any options rsync accepts.
-v, --verbose will also print the command that'll be used to sync
Examples:
sync-to other-pc ~/Documents
sync-to other-pc ~/Music --exclude '*.wav'
sync-from other-pc ~/Music --dry-run --delete
END
exit(1)
end
def verbose?()
ARGV.any?{ |opt| /^--verbose|-\w*v\w*$/.match(opt) }
end
#
# parse options
#
print_usage_and_die and die if ARGV.length < 2
host = ARGV.shift
dir = ARGV.shift
rsync_excludes = RSYNC_EXCLUDE_PATTERNS.map{ |pattern| "--exclude='#{pattern}'" }.join(' ')
rsync_user_options = ARGV.join(' ')
rsync_src_dest = case PROGRAM_NAME
when /to$/
"\"#{dir}/\" #{host}:\"#{dir.shellescape}\""
when /from$/
"#{host}:\"#{dir.shellescape}/\" \"#{dir}\""
else
puts "Error: unknown command"
print_usage_and_die
end
#
# copy
#
cmd = [
RSYNC,
RSYNC_BASIC_OPTIONS,
rsync_excludes,
rsync_user_options,
rsync_src_dest
].join(' ')
puts cmd if verbose?
system(cmd)
@riyad

This comment has been minimized.

Show comment
Hide comment
@riyad

riyad Jan 31, 2015

Installation

  • Save this script as something like sync-to somewhere in $PATH.
  • Link it to sync-from in the same location. (i.e. ln sync-to sync-from)

Examples

sync-to other-pc ~/Documents
sync-to other-pc ~/Music --exclude '*.wav'
sync-fom other-pc ~/Music --dry-run --delete

Owner

riyad commented Jan 31, 2015

Installation

  • Save this script as something like sync-to somewhere in $PATH.
  • Link it to sync-from in the same location. (i.e. ln sync-to sync-from)

Examples

sync-to other-pc ~/Documents
sync-to other-pc ~/Music --exclude '*.wav'
sync-fom other-pc ~/Music --dry-run --delete

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment