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

Community
  • 1
  • 1
LampShade
  • 2,675
  • 5
  • 30
  • 60

3 Answers3

2

Try this to redirect stderr to stdout:

OUTPUT="$(osascript myAppleScript.scpt 2>&1)"
echo "$OUTPUT"
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • 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) – LampShade Jun 26 '15 at 16:49
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.

foo
  • 3,171
  • 17
  • 18
  • The idiomatic way to check the exit status in shell script is simply `if`. See also https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern – tripleee Jun 17 '19 at 04:55
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.

ccpizza
  • 28,968
  • 18
  • 162
  • 169