/

AppleScript by Example: Episode 1

AppleScript by Example: Episode 1

If you’re new to AppleScript like me, you might find it challenging to grasp at first. The mental model behind AppleScript is quite different from what most developers are used to. Nevertheless, there are times when you’ll need to write AppleScript code to automate tasks on your Mac.

Today, I had to write an AppleScript, and after some googling, stackoverflowing, and chatgpting, I came up with the following solution:

1
2
3
4
5
6
7
8
tell application "Finder"
set currentFinderWindowPath to (POSIX path of (target of front window as alias))
end tell

tell application "Terminal"
do script "cd " & currentFinderWindowPath
activate
end tell

Let’s break down what this script does so that I can refer back to it in the future.

Firstly, we ask the Finder app to retrieve the absolute path of the currently active window using the following line of code:

1
POSIX path of (target of front window as alias)

Alternatively, you could write it as:

1
tell application "Finder" to get the POSIX path of (target of front window as alias)

This alternative approach would be useful if you wanted to incorporate this command into a shell script, for example, using osascript -e, and combine it with other scripts.

To illustrate, here’s an example of how I used it in another script:

1
2
finderPath=`osascript -e 'tell application "Finder" to get the POSIX path of (target of front window as alias)'`
open -n -b "com.microsoft.VSCode" --args "$finderPath"

Moving on, we store the result of the previous command in a variable called currentFinderWindowPath, using the following structure:

1
set currentFinderWindowPath to (...)

Specifically, we assign the value of the path to the currentFinderWindowPath variable like this:

1
set currentFinderWindowPath to (POSIX path of (target of front window as alias))

Finally, we end the tell application "Finder" block since we want to “talk” to another app, which, in this case, is the Terminal. Within the tell application "Terminal" block, we instruct it to run the command cd ... to change the active folder to the one we retrieved from the Finder earlier. We then call activate to bring the Terminal to the front.

According to the AppleScript manual, the activate command “brings an application to the front, launching it if necessary.”

That’s all for this first episode of AppleScript by Example. Stay tuned for more AppleScript adventures!
tags: [“AppleScript”, “Mac automation”, “Terminal”, “Finder”]