AppleScript Tips for Shell Scripting

3 October 2015

OS X is sur­pris­ingly scriptable, in­clud­ing OS X applications. (Especially Apple’s applications). This is the good news. The bad news is that said scripts are dif­fi­cult to write and debug, and they don’t play very well with Unix-style shell scripts. (Manipulating Unix-style file­names is es­pe­cially painful.)

Here’s an example of what can be done: select works like open except that it opens a Finder window with the ar­gu­ments selected:

The Ap­ple­Script code is com­pli­cated and in­volves far more workarounds than it really should but, hey, it does work.


Some tips and tricks in no par­tic­u­lar order.


log to dump output for debugging, though note that some types are coerced into strings for output–compare the output of log obj and log class of obj if not sure.

Script Editor

osascript’s error mes­sages are pretty awful; for a slightly (slightly!) better de­vel­op­ment experience, use the Script Editor application. This gets you syntax highlighting, and slightly better log messages.

For best results click on the “page” icon in the bottom of the window to reveal the “messages” tab:

(Unfortunately Script Editor can’t open files that start with a shebang (see below)–you’ll need to copy and paste Ap­ple­Script to and from a text editor into Script Editor.)

Shell script­ing

There’s a few dif­fer­ent ways you can run Ap­ple­Script from the command line. First of all, you can use the stan­dard #! shebang with osascript as the interpreter:

To read arguments, use the run method:

You might often find that you often want to do some pre-processing via bash, es­pe­cially for any­thing that in­volves filenames. This can be achieved (as in the select example) via a bash “heredoc”:

Ap­pli­ca­tions API

Use Script Editor’s “File | Open Dictionary…” to figure out what dif­fer­ent ap­pli­ca­tions let you do via AppleScript. Apple ap­pli­ca­tions often expose a rea­son­ably large API; for others you might get some­thing minimal, or even nothing at all.

Spotify, for example, only lets you play/pause/next/prev. You can also get some in­for­ma­tion about the currently-playing track. One the other hand Apple Photos has a fairly rich API. (Example script.)

Working with file­names

Need the current working directory?

set pwd to do shell script "pwd"

Create file object from Unix-style path (with “/”):

(POSIX file unixpath)

Get Unix-style path from a file object:

(POSIX path file)

For more in­for­ma­tion on han­dling filenames, see: