10.4: Use Automator to open chosen folder in Terminal

Aug 31, '05 09:46:00AM

Contributed by: juanfal

Tiger only hintWant an Automator plug-in to cause Terminal to cd into the selected folder (or the containg folder, if you have a file selected).

It's a pretty simple thing to do, with only two elements. Launch Automator and add these two steps to the workflow area via drag and drop:

  1. In the Library column, select Finder, then drag the Action named Get Selected Finder Items into the right-side work area.

  2. Click the Automator entry in the Library column, then drag the Run AppleScript action to the work area. The contents of the script shoudl be:
    on run {input, parameters}
      tell application "Terminal"
        if (the (count of the window) = 0) or 
         (the busy of window 1  = true) then
          tell application "System Events"
            keystroke "n" using command down
          end tell
        end if
        do script "cd \"" & (POSIX path of 
         (input as string)) & "\"" in window 1
      end tell
      return input
    end run
  3. Next, select File: Save as Plug-in, give your new command a name (I called mine "cd"), and make sure the pop-up shows that it will be a Finder plug-in.
When activated via the contextual menu, this command will issue a cd path_of_finder_selection to the frontmost Terminal window. I like it this 'light' way, since it's less window-cluttering than opening a new window each time.

[robg adds: I made a couple small modifications to the script above. First, I added the quoting to protect paths with spaces in their names. Second, I added the activate line to bring the Terminal to the front after executing the cd command.

If you'd rather have a new Terminal window open each time you use the plug-in, you can simplify the script somewhat. First, remove the if (the (count section (through the endif, as you'll be making a new window anyway. Second, change do script "cd.. into do script with command "cd...". There may be slightly better ways to do this, too, but this worked well for me in testing.

Two older hints have scripts to do similar things, but directly in the Finder via the sidebar. These could also be converted into Automator actions, I believe.]

Comments (28)

Mac OS X Hints