Laptop sync script

August 6th, 2008

UPDATED: fixed a typo that meant directories with spaces weren't syncing (arrrgghhhh); changed example dirs/files

I've needed this sorting for ages - I've spent too long copying files adhoc between my iMac and MacBook. Tonight I wrote a simple ruby script to easily push changes to my laptop and pull them back again. Note that everything is driven from the desktop end - I don't push changes from my laptop to my desktop.

The script is easy enough to modify if you want to use it. Just bear in mind it comes with no warranty of any sort, and I'm not responsible if it deletes everything on your hard drive. It's fairly safe, the -u option to rsync stops it overwriting newer files if you sync in the wrong direction (that won't stop it deleting stuff, though). I ran it just and nothing important disappeared, that I noticed anyway...

All you need to do it is put the file in your path as sync_to_laptop (I used ~/bin), create a symbolic link called sync_from_laptop and make sure they are executable (you knew all this, right?):

    cd ~/bin
    ln -s sync_to_laptop sync_from_laptop
    chmod +x sync_to_laptop sync_from_laptop

Then modify the constants at the top to suit your needs.

I'm sure there's a more elegant way to build the rsync command, but, meh... it works, and I need it for this weekend.

Code follows. Feedback or "why didn't you use XYZ that does all this and more?"-style comments welcome.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

#!/usr/bin/env ruby

LAPTOP_HOSTNAME = "firedrake.local"

SYNC_DIRS = [
  "~/.gnupg",
  "~/.ssh",
  "~/.irbrc",
  "~/.caprc",
  "~/.gemrc",
  "~/.gitconfig",
  "~/.zshrc",
  "~/.zsh_wordchar",
  "~/Documents",
  "~/Library/Application Support/TextMate",
  "~/Music/iTunes"
]

def escape_spaces(string)
  string.gsub(' ', '\ ')
end

def sync_command(src, dest)
  source_dir, destination_dir = escape_spaces(src), escape_spaces(dest)
  
  base_command = "rsync -avuE --delete --exclude '.DS_Store'"
  
  case File.basename($0)
    when "sync_to_laptop"
      %Q(#{base_command} #{source_dir} '#{LAPTOP_HOSTNAME}:#{destination_dir}')
    when "sync_from_laptop"
      %Q(#{base_command} '#{LAPTOP_HOSTNAME}:#{source_dir}' #{destination_dir})
  end
end

def run_command_streaming_output(command)
  IO.popen(command) do |pipe|
    while line = pipe.gets
      puts line
    end
    puts
  end
end

SYNC_DIRS.each do |dir|
  command = sync_command(dir, File.dirname(dir))
  puts "*** #{command}"
  run_command_streaming_output(command)
end

1 Response to “Laptop sync script”

  1. Pawel Kaminski Says:

    Hello Ashley,

    I can see you are still doing what you do best..:) Any chance you are going to Berlin this year? And how does "being your own captain and ship" work? Take care mate Pawel

Sorry, comments are closed for this article.