Title says it all. I just want to know what command to enter to change the working directory to the directory of whatever is open in the front finder window.
-
2Note that there are some alternatives available: 1. If you Command-Drag a file or folder into a terminal, it will send an entire `cd` command for you automatically, 2. You can start in Finder and use the contextual menu to open a terminal in the currently selected folder using the "New Terminal at Folder" Service (enable it in **System Preferences > Keyboard > Services**), 3. You can drag files and folders onto the Terminal application icon or into a terminal window tab bar to open a new terminal at that location. – Chris Page Aug 27 '13 at 23:30
-
See also http://stackoverflow.com/q/420456/754997 – Chris Page Dec 30 '13 at 21:48
3 Answers
My answer is based off an answer to a similar question about how to get the path of the front-most window in Objective-C and Cocoa (which is apparently from a Mac OS X Hints tip which might have been your exact question). I've tested the command and it will work directory paths containing spaces too.
cd "`osascript -e 'tell application "Finder" to POSIX path of (target of window 1 as alias)'`"
Using bash? Add this function to your bash profile.
cdf () {
finderPath=`osascript -e 'tell application "Finder"
try
set currentFolder to (folder of the front window as alias)
on error
set currentFolder to (path to desktop folder as alias)
end try
POSIX path of currentFolder
end tell'`;
cd "$finderPath"
}
-
1Note that in the “inline” version “set myname to” is unnecessary, since you just want it to return the value—you aren’t using the variable. – Chris Page Aug 27 '13 at 23:31
-
-
If I try to use this in fish, it tells me: `fish: Unknown command 'insertion'`... Any suggestions? – rassoh Dec 18 '16 at 12:46
-
@rassoh, fish has slightly different syntax so you'll need to modify the statement. There is an [oh-my-fish](https://github.com/oh-my-fish/oh-my-fish) plugin that provides exactly this [exact capability](https://github.com/oh-my-fish/plugin-osx/blob/master/functions/pfd.fish). – Linville Dec 19 '16 at 15:17
-
Using the Finder's insertion location
property also works very well – this changes the working directory to the folder that is current active in the Finder (the last window or desktop space that was clicked):
cd "`osascript -e "tell application \\"Finder\\" to get POSIX path of (insertion location as text)"`"
or, add the following line to your bash profile (~/.bash_profile):
alias cdf='cd "`osascript -e "tell application \\"Finder\\" to get POSIX path of (insertion location as text)"`"'

- 335
- 3
- 12
In Yosemite, I just drag the folder from Finder window on top of the Terminal icon on my dock and terminal opens to that folder. Neat isn't it? No script or service needed.

- 478
- 4
- 15
-
The question is so I can build a more complex script. GUI shortcuts don't help in that situation. Also, someone already mentioned that – Tomulent Nov 20 '14 at 16:31