Categories
Uncategorized

AppleScript experiences

Today I messed around in AppleScript. To be honest, it has not only been a pleasure.

Current working directory

One of the really annoying things I came across: An AppleScript application does not start within its directory, but within ~ (user’s root).
So if you want to do some work in the script’s real current working directory, you have to change there explicitely.
And even that comes with a drawback. You have to manually extract your script’s working directory.
To make the story short – here’s my solution of putting the working directory into a variable:

set pathOfScript to quoted form of (POSIX path of (path to me))
set cwd to do shell script "echo " & pathOfScript & " | sed 's/\\(\\/.*\\/\\)\\(.*\\)/\\1/g' "

Basically this two lines request the posix path to the script (including the script’s filename) and strip the filename using a regexp.
If you wonder about this crazy regular expression – it just selects the text between the first and the last forward slash (/).
It’s just blown up by massive need for escaping backslashes.
Briefly it’s this: search for (/.*/)(.*) and throw away the last group containing the filename.

Displaying a dialog box

Whenever there’s need for debug output and there’s no debugger (like in Apple’s Script Editor) you can always fire up a dialog box:

display dialog "hello world"

Scripting the Terminal

Apple’s shell (called Terminal) is also scriptable by AppleScript. You can e.g. open Terminal and execute a command taken from a variable ‘_cmd’:

set _cmd to "ls"

tell application "Terminal"
  activate
  do script with command _cmd
end tell

My motivation

Why the heck did I use AppleScript in the first place?
Well – I’ve written a Java application (deployed within a JAR file) but unfortunately I didn’t find an easy way to start this application via double click.
Manually entering the Terminal, exploring to the destination path and entering ‘java -cp FirstJar.jar:SecondJar.jar:. my.main.Class” is really annoying.
So now my AppleScript takes following actions:

  1. Open the Terminal
  2. Get the current working directory and change to it (cd …..)
  3. Start Java handing over the correct classpath and program arguments.