Learning Applescript… One Script At A Time

September 30, 2009

I have been pushing myself of late to take my Mac knowledge to that next level, and as far as I am concerned the path to get there goes straight through Mac OS X’s automation tools, and Applescript in particular.

My strategy to learning Applescript is pretty simple.   I’ve armed myself with Sal Soghoian’s excellent book, AppleScript 1-2-3, and I periodically assign myself small projects to script real world tasks.  Ironically enough, at least until I get a little more experienced, writing a script is not always the fastest or easiest way to get things done.  However, you’ve got to start somewhere and to paraphrase President Kennedy, we do things not because they are easy but because they are hard.

Several weeks ago I downloaded a trial of Hazel after hearing many good things about it on various podcasts and blogs.  Hazel is an application that makes it easy to establish automated rules for folder management, and I had set up a Hazel rule that automatically moved screenshots from my desktop to a designated screenshots folder (thanks go out to Lifehacker for the idea).  I quickly realized this was a perfect candidate for an Applescript project.  Everything Hazel was doing for me in this rule could be automated with Applescript, and it covered scripting tasks I’d never attempted before.

It sounded simple enough, yet it quickly introduced other choices for me to consider:  How do I tell if a file is really a PNG image versus a text file with a .png extension?  How do I handle a failed move operation?  What do I do if there is an unhandled error?  How do I notify a user of success or failure?  Should I use Growl?  How do I know if Growl is running?  Even though this was a very basic script, I couldn’t help but think of the parallels with what Brent Simmons discusses in his article, Anatomy of a Feature.

Thinking through these questions were important — they created additional opportunities to learn.  By the time I was done I had picked up some good Applescript experience, to include:

  • scripting Folder Actions
  • how and why to use Uniform Type Identifiers (UTI)
  • why you should use System Events in Leopard / Snow Leopard instead of the “for info” command
  • how to set up Growl notifications via Applescript
  • how to check if an application was running

I’m now keeping a list of similar-sized scripting projects and doing my best to knock them off one by one.  While the going is sometimes slow and the projects are small in scope, each is steadily moving me along the path to become a better scripter.

BTW, here’s the script (It may not seem like much, but trust me — it took me a little time to get there!).

Previous post:

Next post: