Saturday, April 12, 2008

A Bit More on AppleScript and stdin

I can get even simpler than the earlier script to pass stdin to an AppleScript embedding within a shell script. Consider this:
#!/bin/sh

/usr/bin/osascript > /dev/null <<ASCPT
    set stdinText to "$(cat | sed -e 's/\\/\\\\/g' -e 's/\"/\\\"/g')"
    tell application "TextEdit"
        activate
        make new document with properties {text:stdinText}
    end tell
ASCPT
No need for the temporary file anymore, just use cat from within the AppleScript portion. The result of cat needs to be piped through sed in order to prevent problems with quoting, with a bunch of backslashes to get the special characters right. This may need further tweaking.

I ran into this when I tried using the earlier script for showing the results of the various scripts for the SubEthaEdit LaTeX mode. The earlier script failed when used for showing the results of bibtex. For some reason that I've not been able to work out, the AppleScript Standard Additions are no longer reached and the call to do shell script fails. The new approach works, so far at least.

3 comments:

D. Grady said...

Isn't this a bit easier if you use the osascript environment? You can create a script (call is ascat.sh) containing

#!/usr/bin/env osascript
set stdin to do shell script "cat"
"The following was read by AppleScript: " & stdin

and then from the terminal

$ echo hello | ./ascat.sh
The following was read by AppleScript: hello

Michael Barber said...

Using osascript in the shebang line is fine, but a bit limiting if you want to use a bit of AppleScript as a part of a more complex script. Take a look at this script for an example.

D. Grady said...

Ah, I didn't think of that. I was going to say that even in this case you could do something like

#!/usr/bin/env bash
echo "Here we are in bash"
/usr/bin/osascript -e 'set stdin to do shell script "cat"' \
-e '"AppleScript says: " & stdin'

but then it rapidly becomes more of a hassle to make sure the AppleScript is correctly quoted than to just use sed as you suggest. Thanks for pointing that out!