Applescript dialog, Bash alias/function

applescriptbash

I'm trying to create a short alias for creating System dialogs from the Terminal. I tried to create a Bash function (since an alias didn't seem to take arguments) and add it to my .bash_profile, but it's failing me.

My latest attempt is:

dialog() {
    DIALOGVAR='tell app "system events" to display dialog "'$@'"'
    CMD="osascript -e 'tell app \"system events\" to activate' -e '$DIALOGVAR'"
    $CMD
}

But when I execute it via the Terminal, I get

0:1: syntax error: A unknown token can’t go here. (-2740)

Even though echo'ing the CMD variable gives me a properly formatted command:

osascript -e 'tell app "system events" to activate' -e 'tell app "system events" to display dialog "foo bar"'

Perhaps I'm doing something wrong, perhaps there's an easier way to achieve this. All I'm trying to do is to create an easy to execute command that displays dialogs.

EDIT: Alternative attempt didn't lead to anything either. This one works for arguments without spaces, but fails for multiple arguments.

sysdialog() {
    osascript -e "tell app \"system events\" to activate" -e "tell app \"system events\" to display dialog \"$@\""
}

Best Answer

You can use the run handler to pass arguments:

dialog() {
    osascript -e 'on run args
    try
    tell app "SystemUIServer" to display dialog (item 1 of args)
    end
    activate app (path to frontmost application as text)
    end' "$1"
}

If you want to call it like dialog a b (instead of dialog 'a b'), change $1 to $*.

System Events quits automatically when it is not used, and there is a small delay when it is opened, so telling it to display the dialog would sometimes be slower.

Without the try block there would be an error if the user presses a cancel button. Without activate the previously focused window wouldn't get focus back when the dialog is closed.

You can use something like this to display text dialogs:

answer=$(osascript -e 'try
tell app "SystemUIServer"
set answer to text returned of (display dialog "" default answer "")
end
end
activate app (path to frontmost application as text)
answer' | tr '\r' ' ')
[ -z "$answer" ] && exit