Script applications
Call AppleScript with osascript
Invoke a small AppleScript from the shell, capture its result, and keep data separate from script source.
osascript runs AppleScript and returns its result to the shell. It’s the bridge that lets a zsh script use everything from the previous two lessons.
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 works for one line.
Beyond one line, quoting becomes the main problem. Keep longer scripts in files.
Scripts in files
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. That’s how a path leaves AppleScript and enters the shell.
And || exit lets a failing AppleScript stop the shell workflow. When the script throws, osascript prints the error to stderr and exits non-zero. Your workflow fails at the right line instead of continuing with an empty variable.
File-based scripts can also receive arguments. Anything you pass after the filename arrives in an on run argv handler inside the script. The shell supplies the data, and the AppleScript stays generic. Keep them separate.
Treat the result as untrusted
The value came from another program. Quote it, validate it, and only then use it:
if [[ ! -d "$folder" ]]; then
echo "not a directory: $folder" >&2
exit 1
fi
This looks paranoid for a path from Finder. It isn’t. An app update, a localized string, or an unexpected window type can change what comes back.
Permission follows the caller
When Terminal runs osascript, it’s Terminal that needs Automation permission for the target app. The TCC prompt names Terminal, not your script.
Now put the same script inside a scheduled job. It runs with no one to show a prompt to. This is the most common reason an automation that worked during testing fails silently later.
The signature of that failure is error -1743 in stderr. When you see it, you know exactly what happened: the process that ran the script had no grant.
So test the script in the same context it will really run in. Not only from your interactive shell. We come back to this when we load the LaunchAgent.
Try this: run your front-folder script through osascript, capture the path, then cd into it. Then break the path validation on purpose by pointing it at a file, and confirm the script exits with the message.
Lesson completed