Terminal tip:
Navigating to the current Finder window

A few days ago, I read an article about zsh in a German IT magazine. The author pointed out that with zsh, you can easily cd to the frontmost Finder window. Well … that’s not too exciting – this has been possible for years on OS X, with any shell.

All it takes is a shell alias like this one:

alias go-finder='cd "$(osascript -e "tell application \"Finder\"" -e "try" -e "set targetPath to POSIX path of (target of window 1 as string)" -e "on error" -e "set targetPath to \"\"" -e "end try" -e "end tell")" && pwd'

(For unexperienced shell/Terminal users: this code has to go into one of the files which are read when starting a new shell. On OS X, one would typically use ~/.profile, i.e.: a file called .profile in your home directory.)

Then, open a new Terminal window or source ~/.profile, invoke go-finder and here you go. If you have never encountered osascript before: it’s a command-line runner for OSA scripts, which means: for AppleScript and (more recently) for JavaScript. With its ability to bridge the gap between Terminal and GUI, osascript is one of those hidden gems that make OS X really shine.

Back to news overview