LampShade
LampShade

Reputation: 2775

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

Upvotes: 1

Views: 2555

Answers (3)

Cyrus
Cyrus

Reputation: 88654

Try this to redirect stderr (2) to stdout (1):

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

Upvotes: 3

ccpizza
ccpizza

Reputation: 31706

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.

Upvotes: 0

foo
foo

Reputation: 3259

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.

Upvotes: 0

Related Questions