# AppleScript by example, episode 1

> Learn AppleScript by example with a script that grabs the front Finder window path and opens it in Terminal, then run it from the shell with osascript.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2023-02-01 | Topics: [Mac](https://flaviocopes.com/tags/mac/) | Canonical: https://flaviocopes.com/applescript-by-example-episode-1/

I have never written any AppleScript, although I have used 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:

```javascript
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:

```javascript
POSIX path of (target of front window as alias)
```

You could also write that as 

```javascript
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: 

![Terminal showing osascript command returning the POSIX path of Finder's front window](https://flaviocopes.com/images/applescript-by-example-episode-1/1.webp)

Like I did in another script I wrote:

```javascript
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:

```javascript
set currentFinderWindowPath to (...)
```

in this way:

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

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

```javascript
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 to the folder we retrieved from Finder before.

Then we run `activate` 

The [AppleScript manual](https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_cmds.html#//apple_ref/doc/uid/TP40000983-CH216-SW60) says this command “Brings an application to the front, launching it if necessary”
