Automatically cd to active Finder directory in new Terminal window
Sep 23, '11 07:30:00AM
Contributed by: canisbos
There exist small apps that will open a new Terminal window or tab and automatically cd to the directory of the active Finder window. This hint describes a way to have the Terminal always cd to the directory of the active Finder window whenever you open a new Terminal window or tab -- without the use of an app or any other third-party solution.
In other words, whenever you open a Terminal window or tab, if there is an open Finder window, the Terminal will start in the directory shown in the Finder window.
To make this happen, all you need to do is add the following line somewhere in your .bash_profile file in your home directory:
cd `osascript -e 'tell application "Finder" to if window 1 exists then if target of window 1 as string is not ":" then get POSIX path of (target of window 1 as alias)'`
To edit your .bash_profile file, open Terminal and enter the command:
open ~/.bash_profile -a TextEdit
Paste the code on an empty line anywhere in the file, and save the file. If Terminal complains that .bash_profile doesn't exist, create it with this command:
touch ~/.bash_profile
Then edit it as described.
If you want a quick way to cd to the active Finder directory manually, add the following code to your .bash_profile:
alias cdf='cd `osascript -e "tell application \"Finder\" to if window 1 exists then if target of window 1 as string is not \":\" then get POSIX path of (target of window 1 as alias)"`'
Upon opening a new Terminal window, you'll be able to cd to the active Finder directory by just entering cdf at the prompt. If you'd rather use a different shortcut, substitute your own string in the above code, after 'alias ' and before the equals sign.
(The alias hint is similar to this hint, but discovered independently.)
Note: If you use the 'cdf' alias when there is no open Finder window, or when the active Finder window is showing something other than a directory, you will be taken to your home directory.
[crarko adds: I tested this, and it works as described.]
Comments (14)
Mac OS X Hints
http://hints.macworld.com/article.php?story=20110817133623734