A script to open current Finder folder in the Terminal

Nov 15, '03 11:22:00PM

Contributed by: ramsperger

I have been using this script for about a year and everyone I have passed it on to has found it useful. This script does two things:

  1. Running it opens a new Terminal window and changes the directory to match the dirctory of the front most Finder window
  2. Dragging onto it changes the directory to the path of the item (or its containing folder)
I've now placed it in the sidebar of the Finder windows (previously in the menubar at the top), but it also works from the Dock. You can download the compiled script or compile it yourself with the code in the remainder of the hint...

[robg adds: There's an earlier hint with a similar script, though this one handles paths more robustly, I think...]


(*
Open in Terminal
Copyright 2002 Gregory Ramsperger <oit@jitjat.com>

To use:
     * Drag  a single container onto Open In Terminal to go
      to it in Terminal
       * Drag Open In Terminal to the toolbar of any finder
      window to add it to the toolbar
   * Place Open In Terminal in the Dock and use it to
      open the frontmost window or drag containers to it to open them.
*)

property badPathChars : ¬
{"\\","`","!","$","&","(",")","{","}","|","'","\"",";","<",">","?"," "}

-- drag-and-drop open
on open theList
  -- only open the first item in the list
  set dir to (item 1 of theList) as text
  
  -- cd in the terminal
  my oit(dir)
end open

-- direct run
on run
  try
    -- get the frontmost window of the finder
    tell application "Finder"
      set dir to the target of Finder window 1 as text
    end tell
    
    -- convert the path from Mac to unix
    my oit(dir)
  on error
    -- if there is no window open in the finder, open the desktop
    my oit(path to desktop)
  end try
end run

-- run a command in the terminal
on oit(d)
  tell application "Finder"
    
    -- make sure that the item is a directory
    if d does not end with ":" then
      set d to (container of item d) as text
    end if
  end tell
  
  set p to (POSIX path of d)
  
  -- the extra safe path translation method
  -- add a \ before every character
  repeat with c in badPathChars
    set AppleScript's text item delimiters to c
    set tempitemList to every text item of p
    set AppleScript's text item delimiters to ("\\" & c)
    set p to the tempitemList as string
    set AppleScript's text item delimiters to ""
  end repeat
  
  tell application "Terminal"
    activate
    do script with command ("cd " & p)
  end tell
end oit
[robg adds: Paste the above into Script Editor and save it (I saved it as an Application). Drop in the sidebar, menu bar, whereever ... a very useful addition!]

Comments (6)


Mac OS X Hints
http://hints.macworld.com/article.php?story=2003110619193517