1

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

3 Answers 3

3

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

OUTPUT="$(osascript myAppleScript.scpt 2>&1)"
echo "$OUTPUT"
Sign up to request clarification or add additional context in comments.

1 Comment

I can also wrap my apple script with a try on error, but this is better for me because I want my BASH script to handle the entire thing, and this gives me the entire error including saying "myAppleScript.scpt: execution error:" which I can easily parse for (apple script try on error doesn't include that part)
0

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.

1 Comment

The idiomatic way to check the exit status in shell script is simply if. See also stackoverflow.com/questions/36313216/…
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.