Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Create a command to 'cd' to frontmost Finder window UNIX
I've seen a few contextual menus, Automator plug-ins, and AppleScript applications written to do this, but they all require me to change my workflow. My typical workflow is:
  1. Open desired window in Finder
  2. Command-tab to Terminal
  3. Type a command to get me to aforementioned window
So here's my solution: Put the following snippet in your .bashrc (or .bash_profile) file to enjoy that seamless no-mouse feeling:
cdh() # cd's to frontmost window of Finder
{
cd "`osascript -e 'tell application "Finder"' \
-e 'set myname to POSIX path of (target of window 1 as alias)' \
-e 'end tell' 2>/dev/null`"
}
Close and reopen the Terminal, or type source .bashrc to activate the new command. From now on, you can just type cdh in Terminal, and automagically cd to the frontmost Finder window.

[robg adds: The code above is the result of an exchange between the author and I; it seems to work fine on both 10.3 and 10.4 machines, though I'm sure there may be better ways to achieve the same results. Note that I've broken the code onto multiple lines for a narrower display; it should work fine with a copy and paste, but if it breaks, remove the backslashes and line breaks from the cd "`... section, and make it one long line.]
    •    
  • Currently 1.00 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (2 votes cast)
 
[12,147 views]  

Create a command to 'cd' to frontmost Finder window | 24 comments | Create New Account
Click here to return to the 'Create a command to 'cd' to frontmost Finder window' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Create a command to 'cd' to frontmost Finder window
Authored by: lee1 on Oct 04, '05 08:26:37AM

This problem is solved in a more general way here:

http://www.chemistry.ucsc.edu/~wgscott/xtal/terminal_finder_interactions.html



[ Reply to This | # ]
Create a command to 'cd' to frontmost Finder window
Authored by: wgscott on Oct 04, '05 08:56:39AM
Oh, thanks, I was going to post that. The credit for that goes to Gary Kerbaugh. Also, you can now install his scripts with fink. IIRC it was a hint once.

[ Reply to This | # ]
dangerous script
Authored by: mzs on Oct 04, '05 08:50:52AM
Whenever you do POSIX path in an applescript and you want to pass the results to something you do from the shell, you need to escape it. The way to do that is with the "quoted form of" recipe. Beyond that the original script is dangerous since it evaluates the unescaped path which could have commands in it.

Anyway here is an improved script that also fixes that mistake.


# cd's to frontmost window of Finder
cdh() {
        eval cd `osascript -e '
try
        tell application "Finder"
                quoted form of POSIX path of (target of window 1 as alias)
        end tell
on error
        "."
end try
'`
}


[ Reply to This | # ]
dangerous script - actually not
Authored by: mzs on Oct 04, '05 11:56:06AM
Since this uses the form "``" instead of just `` that aspect of the original script is okay. No word splitting etc happens in that case. For example:

$ echo 'foo  bar'
foo  bar
$ echo `echo 'foo    bar'`
foo bar
$ echo "`echo 'foo    bar'`"
foo    bar
So it is not incorrect, nor is it dangerous precisely because it DOES not do an eval. I feel pretty dumb now.

[ Reply to This | # ]
another version
Authored by: hayne on Oct 04, '05 09:10:26AM
Here's my version of that Bash function. (This uses the more modern $( ... ) mechanism for command substution and uses a "here" document to make the layout clearer.)

# cdf: cd's to frontmost window of Finder
cdf ()
{ 
    currFolderPath=$( /usr/bin/osascript <<"    EOT"
        tell application "Finder"
            try
                set currFolder to (folder of the front window as alias)
            on error
                set currFolder to (path to desktop folder as alias)
            end try
            POSIX path of currFolder
        end tell
    EOT
    )
    echo "cd to "$currFolderPath""
    cd "$currFolderPath"
}


[ Reply to This | # ]
missing backslashes
Authored by: hayne on Oct 04, '05 09:16:13AM
The [ code ] tags didn't work to completely preserve what I posted above. It removed the backslashes before the two interior quotes in the 'echo' line. It should be:

echo "cd to "$currFolderPath""


[ Reply to This | # ]
missing backslashes (take 2)
Authored by: hayne on Oct 04, '05 09:20:04AM

Arrgh!
I tried to make the backslashes come out by putting double-backslashes and this seemed to work in the preview, but as you see, the backslashes in my above comment still got eaten up upon submission.
I'm giving up on this, but just add in a backslash before the two " symbols that are inside the quoted string in that 'echo' line.



[ Reply to This | # ]
missing backslashes
Authored by: jacobolus on Oct 04, '05 11:36:51AM

To get backslashes, you need to put double backslashes, then add them again when they disappear from the input box in the preview page.



[ Reply to This | # ]
missing backslashes
Authored by: hayne on Oct 04, '05 01:37:25PM
Okay I'll try it one more time, using that technique:
The 'echo' line should be:

echo "cd to \"$currFolderPath\""


[ Reply to This | # ]
Create a command to 'cd' to frontmost Finder window
Authored by: jacobolus on Oct 04, '05 11:34:52AM
because this script only does one line, we can just do:
cdh() # cd's to frontmost window of Finder
{
cd "`osascript -e 'tell application "Finder" to set myname to \
POSIX path of (target of window 1 as alias)' 2>/dev/null`"
}
or something similar

[ Reply to This | # ]
Create a command to 'cd' to frontmost Finder window
Authored by: jacobolus on Oct 04, '05 11:38:48AM

My code there got its backslash taken out. But add it in to make the script work.



[ Reply to This | # ]
Create a command to 'cd' to frontmost Finder window
Authored by: jacobolus on Oct 04, '05 11:52:05AM
If we want to make sure to get the "quoted form", I guess we can do this:
cdh() # cd's to frontmost window of Finder
{
eval cd "`osascript -e 'tell application "Finder" to set return to quoted \
form of POSIX path of (target of window 1 as alias)' 2>/dev/null`"
}


[ Reply to This | # ]
Create a command to 'cd' to frontmost Finder window
Authored by: gidds on Oct 04, '05 01:13:29PM
There's already a way to do this: type 'cd ' at the command line, and then drag a folder onto it. (You can drag a folder from a Finder window or the desktop, or from a title bar.) It automatically adds escape characters as needed, and is also useful for commands other than 'cd'. (You can drag files as well as folders, and more than one at once.)

A dedicated script may be better choice if you're doing this specific thing a lot, but it's always good to know what built-in features are available, and for casual use it beats having to install extras, forget where they are, etc..

---
Andy/

[ Reply to This | # ]

reminders of aliases
Authored by: hayne on Oct 04, '05 02:02:29PM
I keep all my Bash aliases and functions in the file "~/.aliases.bash" which I source in my ~/.profile

And one of the things in that file is the following Bash function which I use to remind myself of what aliases (or other commented reminders) I have in that file:


# showa: to remind yourself of an alias (given some part of it)
showa () { /usr/bin/grep -i -a1 $@ ~/.aliases.bash | grep -v '^\s*$' ; }


[ Reply to This | # ]
reminders of aliases
Authored by: datawrangler on Oct 04, '05 03:45:46PM

Also, the bash shell command 'alias' will display a list of all aliases you have set



[ Reply to This | # ]
aliases vs functions
Authored by: hayne on Oct 07, '05 07:34:55AM

But the Bash command 'alias' only shows aliases (obviously!)
and many of the things in my .aliases.bash are actually Bash functions
since Bash aliases are so limited - e.g. no way to insert command-line args



[ Reply to This | # ]
Create a command to 'cd' to frontmost Finder window
Authored by: datawrangler on Oct 04, '05 03:43:04PM

I use a nifty Contextual Menu Item called TerminalHere <http://www.macupdate.com/info.php/id/9550>. Works great for me



[ Reply to This | # ]
Create a command to 'cd' to frontmost Finder window
Authored by: dmmorse on Oct 04, '05 07:32:45PM
Or you can use the tools linked to and discussed in this old (2003) hint:

http://www.macosxhints.com/article.php?story=20030915193326598

[ Reply to This | # ]
Create a command to 'cd' to frontmost Finder window
Authored by: szedula on Oct 05, '05 02:40:44PM
I have this script in the Finder window toolbar. When clicked, it will open a new terminal window (if none is open) and change the directory. If one or more files/folders are draged to the icon, terminal windows are opened and the directories changed to the folder or the folder containing the file. I wrote/modified this from this hint and previously posted hints.

-- script was opened by click in toolbar
on run
   tell application "Finder"
      try
         set currFolder to (folder of the front window as string)
      on error
         set currFolder to (path to desktop folder as string)
      end try
   end tell
   CD_to(currFolder, false)
end run

-- script run by draging file/folder to icon
on open (theList)
   set newWindow to false
   repeat with thePath in theList
      set thePath to thePath as string
      if not (thePath ends with ":") then
         set x to the offset of ":" in (the reverse of every character of thePath) as string
         set thePath to (characters 1 thru -(x) of thePath) as string
      end if
      CD_to(thePath, newWindow)
      set newWindow to true -- create window for any other files/folders
   end repeat
   return
end open

-- cd to the desired directory in terminal
on CD_to(theDir, newWindow)
   set theDir to quoted form of POSIX path of theDir as string
   tell application "Terminal"
      activate
      if ((count of the window) = 0) or (the busy of window 1) or newWindow then
         tell application "System Events"
            keystroke "n" using command down
            delay 1 -- sometimes "cd" is lost
         end tell
      end if
      do script "cd " & theDir in window 1
   end tell
end CD_to


[ Reply to This | # ]
Create a command to 'cd' to frontmost Finder window
Authored by: Blah on Oct 07, '05 11:25:16PM

Sa-weeet!

Very nice job. As a long-time Mac developer, I've only recently started to take advantage of using the Finder's toolbar area for scripts (and can't understand why it's taken me this long to give it a try). As far as this script goes, I guess one might want to open a -new- terminal session at times, but then again, not always. Just thinking out loud....

In any case, this is a keeper, thanks.



[ Reply to This | # ]
Create a command to 'cd' to frontmost Finder window
Authored by: szedula on Oct 08, '05 05:13:24AM

If you'd prefer that as the default response, you can easily get that by changing the "false" argument in calls to "CD_to" to "true".



[ Reply to This | # ]
Create a command to 'cd' to frontmost Finder window
Authored by: suarez on Oct 09, '05 11:26:30AM
One problem with using osascript -e is that it's a tiny bit slow. I know, most people won't notice the speed difference, especially when you see the timing results below. What I use instead is:
tell application "Finder"
   try
      POSIX path of (target of window 1 as alias)
   on error
      POSIX path of (path to desktop folder as alias)
   end try
end tell
and save that as a script in my ~/bin folder. Then, in my .bashrc file, I alias cdf to use the script with:
alias cdf='cd "`osascript ~/bin/cdf.scpt`"'
(That's back-tick, double-quote, and single-quote, from inside to out.) Rather than have the 2>/dev/null code ignore the error message, I prefer to go to the desktop if there's no open Finder window. I tried the original solution, and it ran a little slower (by a mean of 85 ms over 10 trials) than this one. I thought I had noticed a little difference, so that's why I timed it.
This, combined with the TerminalHere contextual menu, satisfies my wish-list. There's another AppleScript floating around that does the opposite of this -- opens the current folder in Finder, but this works just fine for me and it's fast:
$ open .


[ Reply to This | # ]
Create a command to 'cd' to frontmost Finder window
Authored by: SimonDorfman.com on Dec 04, '05 01:20:41AM
very cool script! I altered that last section to open a new tab in iTerm instead of Terminal:

-- script was opened by click in toolbar
on run
	tell application "Finder"
		try
			set currFolder to (folder of the front window as string)
		on error
			set currFolder to (path to desktop folder as string)
		end try
	end tell
	CD_to(currFolder, false)
end run

-- script run by draging file/folder to icon
on open (theList)
	set newWindow to false
	repeat with thePath in theList
		set thePath to thePath as string
		if not (thePath ends with ":") then
			set x to the offset of ":" in (the reverse of every character of thePath) as string
			set thePath to (characters 1 thru -(x) of thePath) as string
		end if
		CD_to(thePath, newWindow)
		set newWindow to true -- create window for any other files/folders
	end repeat
	return
end open

-- cd to the desired directory in iterm
on CD_to(theDir, newWindow)
	set theDir to quoted form of POSIX path of theDir as string
	tell application "iTerm"
		activate
		-- talk to the first terminal 
		tell the first terminal
			try
				-- launch a default shell in a new tab in the same terminal 
				launch session "Default Session"
			on error
				display dialog "There was an error creating a new tab in iTerm." buttons {"OK"}
			end try
			tell the last session
				try
					-- cd to the finder window
					write text "cd " & theDir
				on error
					display dialog "There was an error cding to the finder window." buttons {"OK"}
				end try
			end tell
		end tell
	end tell
end CD_to


[ Reply to This | # ]
Create a command to 'cd' to frontmost Finder window
Authored by: Bioinformatics on Jan 07, '06 11:57:34PM

Don't forget that if you select a folder name in Finder, copy it (cmd-C) you can then paste that name in Terminal (cmd-V). This does have the drawback that you need to have the parent window open in Finder, though.



[ Reply to This | # ]