13.14. Running Scripts from Terminal

Mac OS X contains a command called osascript that allows you to execute AppleScript commands and files from the command line. If you're used to using the Terminal application to enter UNIX commands, you may find the osascript command to be a nifty little program.

The general format of the osascript command is as follows:

osascript scriptFile

Here scriptFile is a POSIX path to a script file, perhaps one that you previously created in Script Editor. To execute a single AppleScript statement, you use this form of the osascript command:

osascript -e commands

Here's a command you can type to the shell to have iTunes play the song called "The Reason":

osascript -e 'tell app "iTunes" to play track "The Reason" of first library playlist'

If you know how to write shell scripts, you can create a small shell script called play, for example, that takes the name of the song as its argument and executes an osascript command like that shown previously to play the specified song.

Here, the entire AppleScript statement is enclosed in a pair of single quotes, but they're removed before the statement gets executed. Using single quotes is generally recommended because they hide any double quotes inside the AppleScript statement from the command line shell.

You can use osascript to execute more than a single line. Simply type your open single quote, write as many lines as you need, and then type another single quote to close everything off. The entire set of lines ...

Get Beginning AppleScript® 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.