'Get output from executing an applescript within a bash script

I tried this technique for storing the output of a command in a BASH variable. It works with "ls -l", but it doesn't work when I run an apple script. For example, below is my BASH script calling an apple script.

I tried this:

OUTPUT="$(osascript myAppleScript.scpt)"
echo "Error is ${OUTPUT}"

I can see my apple script running on the command line, and I can see the error outputting on the command line, but when it prints "Error is " it's printing a blank as if the apple script output isn't getting stored.

Note: My apple script is erroring out on purpose to test this. I'm trying to handle errors correctly by collecting the apple scripts output



Solution 1:[1]

Try this to redirect stderr to stdout:

OUTPUT="$(osascript myAppleScript.scpt 2>&1)"
echo "$OUTPUT"

Solution 2:[2]

On success, the script's output is written to STDOUT. On failure, the error message is written to STDERR, and a non-zero return code set. You want to check the return code first, e.g. if [ $? -ne 0 ]; then..., and if you need the details then you'll need to capture osascript's STDERR.

Or, depending what you're doing, it may just be simplest to put set -e at the top of your shell script so that it terminates as soon as any error occurs anywhere in it.

Frankly, bash and its ilk really are a POS. The only half-decent *nix shell I've ever seen is fish, but it isn't standard on anything (natch). For complex scripting, you'd probably be better using Perl/Python/Ruby instead.

Solution 3:[3]

You can also use the clipboard as a data bridge. For example, if you wanted to get the stdout into the clipboard you could use:

osascript myAppleScript.scpt | pbcopy

In fact, you can copy to clipboard directly from your applescript eg. with:

set the clipboard to "precious data"

-- or to set the clipboard from a variable
set the clipboard to myPreciousVar

To get the data inside a bash script you can read the clipboard to a variable with:

data="$(pbpaste)"

See also man pbpase.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cyrus
Solution 2 foo
Solution 3 ccpizza