Command-Line AppleScript: run, read arguments, print, exit

More from the retroversion archives, continuing the discussion from Command-Line JXA: run, read arguments, print, exit:

Here’s how to make a command-line standalone AppleScript. Save the following to, for instance, args.applescript (as text, Unix line endings).

#!/usr/bin/env osascript
on run argv
    argv as text
end

Then,

> chmod +x args.applescript
> args.applescript 1 2 3
123
>

Now, for a bit of debugging humor. I actually started with this script:

#!/usr/bin/env osascript

on run argv
	set oldDelims to AppleScript's text item delimiters
	set AppleScript's text item delimiters to ","
	try
		set theArgs to argv as text
	on error
		set theArgs to "error"
	end try
	set AppleScript's text item delimiters to oldDelims
	theArgs
end run

The result of args.applescript 1 2 3 was 1,2,3. Fine. I added some other stuff, which happened not to work, so I changed the last line from theArgs to argv and ran the script. I got back 1, 2, 3. Huh? Why is this “the same” as the original script?

Well, I failed to notice the spaces before the commas, and went down a rat hole. Eventually I did notice the spaces. Apparently returning argv unmodified returns the arguments separated by commas. (No idea where that comes from.) And it just happened that I used commas in my original script. So I couldn’t figure out what was going on. Blugh.

By the way, if you try this trick make sure the entire script is inside the run handler.

Do I know how adding a “shebang” line can turn an AppleScript into a shell script this way? Not really.

1 Like

This is bogus. Or maybe partially bogus. TBD.

It is bogus. There doesn't appear to be anything special about shebang AppleScripts. And they their run handlers can be explicit or implicit.

I believe the run handler must be explicit IF you're passing arguments to the script on the command-line.

Script:

#!/usr/bin/env osascript
on run argList
   set theNum to item 1 of argList
   beep theNum
end

Invocation (after CD'ing to the directory the script is in).

./Test_Text_AppleScript.sh 2

-Chris