views:

46

answers:

1

I would like to pass the name of an application to an applescript and then perform some actions on it in the script. I've tried the following:

set app_name to item 1 of argv
tell application app_name to ...

This doesn't work. I've tried

set app_name to quoted form of item 1 of argv

which seems to append single quotes, (doesn't work) and,

set app_name to "\"" & item 1 of argv & "\""

that doesn't work either, even though the double quotes are appended.

however if I just write

tell application "Safari" to ...

the application launches. I'm new to Applescript and I'm not sure what's happening here.

A: 

First, you can't use a variable in a "tell" block. It doesn't work because Applescript can't evaluate the variable and thus can't make sense of any of the commands because it doesn't know which application to use to evaluate the commands. As an example try running this script... it won't work...

set theApplication to "Safari"
tell application theApplication
    count of tabs of window 1
end tell

When you want to use a variable like this you need some way to tell applescript how to compile the tell block of code. As such you use a "using terms from" command like this...

set theApplication to "Safari"
using terms from application "Safari"
    tell application theApplication
        count of tabs of window 1
    end tell
end using terms from

The easiest way to do this, for example if you might pass in either "Safari" or "TextEdit", is to do it this way...

set theApplication to "Safari"

if theApplication is "Safari" then
    tell application "Safari"
        count of tabs of window 1
    end tell
else if theApplication is "TextEdit" then
    tell application "TextEdit"
        text of front document
    end tell
end if
regulus6633
Thanks for this, I didn't know of that limitation. I was hoping for a solution that didn't involve if-else statements in the event that I intend to run an arbitrary application.
David K