I was trying to slap a prettier interface onto a bash script for a client. I only bothered to use an AppleScript instead of just sending it to Growl because I needed them to be able to make a choice that I’m going to act on in my script. Even if it was just for display, I didn’t particularly want them to have to install Growl just for my little script.
This is ugly because I had to use a temporary file to store the AppleScript to display the dialog. It is also ugly because we can’t just display the dialog – we get an error message if we try – but we can tell another application to display the dialog. I picked System Events because it’s always running anyway.
This method also allows us to use a program-generated message instead of something static.
And just for the heck of it, I stuff the name of the button the user clicks into a variable, in case you want to use this snippet to display choices for the user.
#! /bin/bash
msg="Giant cracks appeared in the earth’s surface!"
# use $$ here so that the process ID of this script is part of the file name.
# this makes it a lot harder to accidentally step on another instance
# of the script that’s trying to also display something to the user.
tf=/tmp/ziggurat$$
# note that there should be 3 lines between EOF and EOF, in
# in case this is mangled by blogger
cat>$tf <<EOF
tell application "System Events"
display dialog "$msg" with icon stop buttons {"Foo", "Bar", "OK"} default button "OK"
end tell
EOF
foo=`osascript $tf | awk -F":" ’{print $2}’`
echo "foo: $foo"
# don’t forget to trash the temporary file when we’re done with it.
rm $tf
No comments:
Post a Comment