Run AppleScripts from the Terminal with arguments

Feb 05, '04 09:52:00AM

Contributed by: Anonymous

I didn't find this anywhere, so I cooked it up myself. The gist is that you can pre-compile your AppleScripts and pass arguments to them via Terminal -- no need to dynamically generate and compile the scripts via the osascript command.

Read the rest of the hint for the how-to...

[robg adds: I haven't tested this one, and it requires installing a Perl module, so there's a bit of assumed UNIX knowledge...]

Here is how it is done:

  1. Make sure you have the Mac::AppleScript Perl module installed. Do this with the cpan command or how ever you prefer.
  2. Create a text file (osarun) with the following contents:
    #!/usr/bin/perl
    
    use strict;
    use Mac::AppleScript qw/ RunAppleScript /;
    
    if( $#ARGV = 0) ? '"'.join('","',@ARGV).'"' : "";
    
    my $rtn = RunAppleScript( "return run script alias ((POSIX file ""
          .$script.'") as text) with parameters {'.$args.'}' ),"n"
            or die "AppleScript Error: $!";
    
    $rtn =~ s/(^"|"$)//g;
    
    print $rtn,"n";

    Feel free to make this more user friendly.... Save this file on your PATH and make it executable.

  3. Open Script Editor and create your script. Here is an example:
    on run argv
            set rtn to ((count of argv) as text) & " parameters passed.
    The parameters were:
    "
      repeat with arg in argv
                   set rtn to rtn & "      " & (arg as text) & "
    "
          end repeat
        
          return rtn
    end run
    

    The variable argv will be a list of the command line arguments; do anything you want with them. Be sure to save your script as a script or application (just not as text). You can also use osacompile to compile scripts.

  4. Now you can run the AppleScript from the command line:
    osarun Callee.scpt test "second test"

    This should give you the output:

    2 parameters passed.
    The parameters were:
            test
            second test
              

That's it. Now go crazy. Write AppleScripts.

Comments (8)


Mac OS X Hints
http://hints.macworld.com/article.php?story=2004012913110734