Open terminal here (parent directory of drag-and-dropped file), applescript

Alec Jacobson

April 12, 2010

weblog/

Here's a little script I've been meaning to write for while. Often I'm roaming around in the Finder GUI and I want to switch to a terminal. This is not so hard if I already have a terminal window open I can type cd into the command line then drag the current folder I'm looking at in Finder onto the terminal window and I get the full absolute path to that file. Then I hit enter to navigate there on the command line. To make this totally effortless and seemless if Terminal.app is not already running. I wrote the following applescript:
-- if not given files then just act like opening a terminal to the home screen. I.e. `cd`
tell application "Terminal"
  activate
  do script ""
end tell

-- if fiels are drag-and-dropped on this app
on open (these_files)
  -- just use first file if more than one
  set this_path to (quoted form of basedir(POSIX path of (first item of these_files)))
  tell application "Terminal"
    activate
    do script "cd " & this_path
  end tell
end open

on basedir(the_path)
  set last_occurrence to last_offset(the_path, "/")
  if last_occurrence is equal to 0 then
    return "."
  end if
  if last_occurrence is equal to 1 then
    return "/"
  end if
  return items 1 thru (last_occurrence) of the_path as string
end basedir

on last_offset(the_text, char)
  try
    set len to count of the_text
    set reversed to reverse of characters of the_text as string
    set last_occurrence to len - (offset of char in reversed) + 1
    if last_occurrence > len then
      return 0
    end if
  on error
    return 0
  end try
  return last_occurrence
end last_offset
Using some older functions I wrote: last offset of a character in a string base directory of a POSIX path Then I save as an application and drag a shortcut onto my finder bar.