Skip to content

AppleScript by example, episode 1

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”


→ I wrote 17 books to help you become a better developer:

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list