Using redirects to run AppleScripts in the Terminal

May 06, '04 09:56:00AM

Contributed by: orpy

I got really fed up with having to use osascript -e when running AppleScripts remotely via the Terminal. So I thought that I'd give the 'redirect' command a try -- thus allowing me to type and view the script in a way that is much easier to bugfix than a single line. So to run a remote script I now do:

 $ cat << done | osascript
And on hitting Enter, I get a new prompt which allows me to enter the script line-by-line and then finish with whatever word I choose to indicate that the input has ended (in this case, done). What I like about this method is the fact that I can cut and paste huge scripts into the Terminal window and have them run right away. Note that the Terminal will choke on tabbed lines like the set end... one below:
set volumeNames to {}
repeat with i from 1 to (count of disks)
      set end of volumeNames to name of disk i
end repeat
But all you need to do is remove all of the indents before pasting the script into the Terminal window. If you don't fancy running the script immediately, you can easily adapt the commands to save the script to disk first and then run the file:
 $ cat << done > myScript.txt
 $ osascript < myScript.txt
NB: If you are using special characters that may be interpreted wrongly by the shell you should add quote marks to your "end of file" term:
 $ cat << 'done' | osascript
You can do that with either version, obviously.

Comments (5)


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