Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How AppleScript can get STDIN inside the code?

Google suggests

echo "input" | osascript filename.scpt

with filename.scpt

set stdin to do shell script "cat"
display dialog stdin

However, I could get only blank dialog: it has no text. How can I get stdin from AppleScript at the version?

My OS version is OSX 10.8 Mountain Lion.

like image 567
Sea Mountain Avatar asked Dec 04 '22 13:12

Sea Mountain


2 Answers

Sorry, not enough reputation to comment on answers, but I think there's something important worth pointing out here...

The solution in @regulus6633's answer is not the same as piping data into osascript. It's simply stuffing the entire pipe contents (in this case, echo output) into a variable and passing that to osascript as a commandline argument.

This solution may not work as expected depending on what's in your pipe (maybe your shell also plays a part?)... for example, if there are null (\0) characters in there:

$ var=$(echo -en 'ABC\0DEF')

Now you might think var contains the strings "ABC" and "DEF" delimited by a null character, but it doesn't. The null character is gone:

$ echo -n "$var" | wc -c
    6

However, using @phs's answer (a true pipe), you get your zero:

$ echo -en 'ABC\0DEF' | osascript 3<&0 <<EOF
>   on run argv
>     return length of (do shell script "cat 0<&3")
>   end run
>EOF
7

But that's just using zeros. Try passing some random binary data into osascript as a commandline argument:

$ var=$(head -c8 /dev/random)
$ osascript - "$var" <<EOF
>   on run argv
>     return length of (item 1 of argv)
>   end run
>EOF
execution error: Can’t make some data into the expected type. (-1700)

Once again, @phs's answer will handle this fine:

$ head -c8 /dev/random | osascript 3<&0 <<EOF
>  on run argv
>    return length of (do shell script "cat 0<&3")
>  end run
>EOF
8
like image 127
joxl Avatar answered Dec 25 '22 08:12

joxl


According to this thread, as of 10.8 AppleScript now aggressively closes standard in. By sliding it out of the way to an unused file descriptor, it can be saved. Here's an example of doing that in bash.

Here we get at it again with a cat subprocess reading from the magic fd.

echo world | osascript 3<&0 <<'APPLESCRIPT'
  on run argv
    set stdin to do shell script "cat 0<&3"
    return "hello, " & stdin
  end run
APPLESCRIPT

Will give you:

hello, world
like image 43
phs Avatar answered Dec 25 '22 07:12

phs