O'Reilly logo

Mac OS X Hacks by Rael Dornfest, Kevin Hemenway

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Interacting with the Unix Shell from AppleScript

Via the do shell script AppleScript command or scripting the Terminal application itself, you can talk to the command line from inside AppleScript.

AppleScripters can use the Unix shell in two different ways with Mac OS X. The do shell script command executes a Unix shell statement without having to target a specific application. For example, type the following script into a Script Editor window; then compile and run it. It will issue three Unix shell commands, separated by semicolons:

            do shell script "cd $HOME; pwd; ls -l"

The script then receives the return value as a string (a bunch of characters, like a written sentence, surrounded by quotes), which it can then process as needed. Here is a portion of the return value of the latter script:

"/Users/brucep
total 0
drwxr-xr-x 7 brucep staff 264 Nov 24 20:27 AllProps
drwxr-xr-x 5 brucep staff 126 Jan 4 19:57 Applications
drwx------ 17 brucep staff 534 Jan 18 10:24 Desktop
drwx------ 14 brucep staff 432 Jan 18 10:17 Documents
..."

You can also script the Terminal application, which is the command-line utility installed with Mac OS X. The following script will open a new Terminal window and launch the Apache Tomcat Java servlet engine and MySQL database server. Very useful!

ignoring application responses
  tell application "Terminal"
    activate
    do script with command ¨ RETURN
    "/Users/brucep/bin/start_tomcat; /usr/local/bin/safe_mysqld &;"
  end tell
end ignoring

The ¨ character, a line-continuation ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required