If I execute an AS from the command line, either with osascript or by launching an application, can I somehow send command line parameters to the script? Like argv/argc in C-like languages?
Yes. The on run handler can be written as such…
on run xargs
— xargs is a list of arguments passed from the command line.
end run
Excellent. Does it work both with osascript as well as ./Script.app/Contents/MacOS/applet ?
Not sure. I’ve only ever used it with osascript on the command line.
How are you opening the Script.app from the command line?
** EDIT **
I’ve tried many ways to pass arguments to a script app. So far have not found a solution.
OK, I figured out a way.
It’s a little convoluted.
First here is my stay-open Script app i called Args.app
use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
property timer : 0
property argv : missing value
property hasRun : false
on run
delay 1
tell application (path to me as text) to activate
if argv = current application then
beep
display alert (name of me) giving up after 2
else if (class of argv) is list then
choose from list argv
else
try
display alert (argv as text) giving up after 2
end try
end if
set hasRun to true -- this prevents idle handlker from doing its thing till the run handler has run at least once
end run
on setParams(xargs)
set argv to xargs
end setParams
on idle
if hasRun then
if timer = 3 then quit
set timer to timer + 1
return 2
end if
end idle
Notice it has an idle handler. If you don’t need an idle handler then you also don’t need the property “hasRun”.
here is the command line I used to get the parameters to the Script application.
osascript -e “launch application "Args.app"” -e “tell application "Args.app"” -e “setParams({"Mark", "Robert"})” -e “end tell” -e “run application "Args.app"”
The first line of the osacript uses the launch command to start the Args.app (launch command does not automatically cause the run handler to execute)
The third line “setParams({"Mark", "Robert"})” which is inside a tell block, calls the handler “setParams” to receive the parameters i wanted to send as a list.
The fifth line uses the “run” command to execute the run handler, which then set the “hasRun” flag so the idle handler will now execute.