Unix

By the term Unix I mean the command line and other shell-related environments such as Perl and Ruby scripts. Here the important word to know is osascript . This verb is your key to leaping the gulf between Unix and AppleScript. You should read the relevant manpages. (Further details are provided in Chapter 23.)

osascript can execute a compiled script file or can compile and execute a string. The option -e signals that it’s a string, not a script file, and of course if you’re going to type a literal string, this raises all the usual problems of escaped characters. In the Terminal you can usually bypass these problems by single-quoting the string.

The following little conversation in the Terminal illustrates the difference in the formatting of the output depending on whether you supply the -ss flag. I generally prefer this because it does a better job of showing you what sort of reply you’ve really got. The curly braces and the double quotes show clearly that it’s a list of strings:

$ osascript -e 'tell app "Finder" to get name of every disk'
xxx, main, second, extra
$ osascript -ss -e 'tell app "Finder" to get name of every disk'
{"xxx", "main", "second", "extra"}

In a Perl script it’s rather easy to tie oneself in knots escaping characters appropriately so as to construct the correct string and hand it off to osascript. The difficulties are even worse than in the Microsoft Word example earlier in this chapter, because two environments, Perl and the shell, are going to munge ...

Get AppleScript: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.