Quick tips are random posts regarding something I discovered on my way to something bigger. They usually get longer than “quick” would imply, for which I refuse to apologize.

I’d been meaning to write a script to do this for a while, and a post by Dr. Drang inspired me to whip it up. Dr. Drang’s is a TextExpander snippet (which also works fine in shell if you use “quoted form of” to be safe). This method is just a tad more convenient for Terminal usage. It’s a two-line bash function for quickly cd-ing to the location of the front Finder window with a simple command (cdf).

There are a few utilities to do this, like ShellTo and GoToShell, but why run an extra process when it’s this easy? Just throw this in ~/.bash_profile:

# cd to the path of the front Finder window
cdf() {
	target=`osascript -e 'tell application "Finder" to if (count of Finder windows) > 0 then get POSIX path of (target of front Finder window as text)'`
	if [ "$target" != "" ]; then
		cd "$target"; pwd
	else
		echo 'No Finder window found' >&2
	fi
}

[Updated based on suggestions from Rob Trew to fail gracefully when no Finder window is open]

You can also create an alias to do the reverse:

alias f='open -a Finder ./'

Run source ~/.bash_profile and type cdf to change your working directory to match your Finder location. Type f to open a Finder window to your current location in the shell.

Combine the speed and Unix power of the shell with the convenience and added functionality of Finder!

Ryan Irelan has produced a series of shell trick videos based on BrettTerpstra.com posts. Readers can get 10% off using the coupon code TERPSTRA.