Script applications

Call AppleScript with osascript

Invoke a small AppleScript from the shell, capture its result, and keep data separate from script source.

10 minute lesson

~~~

osascript runs AppleScript and returns its result to the shell. It is the bridge that lets a zsh script use everything the previous two lessons covered.

For a one-liner, pass the source with -e:

osascript -e 'tell application "Finder" to get name of startup disk'
# Macintosh HD

Single quotes around the whole expression, double quotes inside for AppleScript strings. That division of labor works for one line. Beyond that, quoting becomes the main problem, so keep longer scripts in files.

File-based scripts can also receive arguments. Anything you pass after the filename arrives in an on run argv handler inside the script, so the shell side supplies the data and the AppleScript side stays generic.

Save the front-window script from the previous lesson as scripts/front-finder-folder.applescript, then run it and capture the result:

folder=$(osascript scripts/front-finder-folder.applescript) || exit
printf "folder=%s\n" "$folder"

Two details in those lines carry the weight. Command substitution captures the AppleScript result as a plain string. And || exit lets a non-zero AppleScript exit stop the shell workflow: when the script throws, osascript prints the error to stderr and exits non-zero, so your workflow fails at the right line instead of continuing with an empty variable.

Treat the result as untrusted input. Quote it, validate the expected path, and only then use it:

if [[ ! -d "$folder" ]]; then
  echo "not a directory: $folder" >&2
  exit 1
fi

The permission model follows the caller. When Terminal runs osascript, it is Terminal that needs Automation permission for the target app, and the TCC prompt names Terminal. The same script inside a scheduled job runs with no one to show a prompt to, which is a common reason automation that worked during testing fails silently later. Error -1743 in stderr is the signature of that failure. Test the script in the same context it will really run in, not only from your interactive shell.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →