Hack 63 Interacting with the Unix Shell from AppleScript

figs/moderate.giffigs/hack63.gif

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 character, is produced on the Mac by pressing Option-Return. The ignoring application responses / end ignoring block will prevent the AppleScript from stalling while it waits for a response from Terminal.

?Bruce W. Perry