Skip to content

AppleScript by example, episode 1

New Course Coming Soon:

Get Really Good at Git

I have never written any AppleScript, although I use a Mac since 2005 I’ve never had the need.

And I’ve always found it quite difficult to grasp, as it’s a very different mental model from what I usually do.

Anyway, today I had to write some, and here’s what I ended up with after some googling, stackoverflowing and chatgpting:

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

I’m going to describe what this does so I’ll remember in the future.

First we ask the Finder app to get the absolute path of the currently active window:

POSIX path of (target of front window as alias)

You could also write that as

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

And this would be a good way to return that in a shell script for example, using osascript -e, to combine that with other scripts:

Like I did in another script I wrote:

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"

Anyway, we assign the result to the variable currentFinderWindowPath using this structure:

set currentFinderWindowPath to (...)

in this way:

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

Then we edn the tell application "Finder" block because we want to “talk” to another app, the Terminal:

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

In this case we tell it to run the command cd ... to change the current active folder in the folder we retrieved from Finder before.

Then we run activate

The AppleScript manual says this command “Brings an application to the front, launching it if necessary”

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!

Here is how can I help you: