macosapplescriptosx-mountain-lion

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.


Solution

  • I know that "set stdin to do shell script "cat"" used to work. I can't get it to work in 10.8 though and I'm not sure when it stopped working. Anyway, you basically need to get the echo command output into a variable which can then be used as an argument in the osascript command. Your applescript needs to handle arguments too (on run argv). And finally, when you use osascript you must tell an application to "display dialog" otherwise it will error.

    So with all that said here's a simple applescript which handles arguments. Make this the code of filename.scpt.

    on run argv
        repeat with i from 1 to count of argv
            tell application "Finder"
                activate
                display dialog (item i of argv)
            end tell
        end repeat
    end run
    

    Here's the shell command to run...

    var=$(echo "sending some text to an applescript"); osascript ~/Desktop/filename.scpt "$var"
    

    I hope that helps. Good luck.