OS X Terminal.app: how to start a new tab in the same directory as the current tab?

I frequently need to open a new tab in the same directory as my current tab to do something else while my current tab is occupied by a long running process. However, by default when you create a new tab, Terminal.app starts at ~/. Any idea how to make it auto jump?


Solution 1:

In OS X 10.7 (Lion), Terminal.app supports this natively: New Windows/Tabs open in: Same working directory

Solution 2:

One must be very careful when passing strings through different environments.

I run 10.4, so my ‘tfork’ script always opens a new window instead. It should be easy to adapt it to use a tab:

#!/bin/sh

# source: http://www.pycs.net/bob/weblog/2004/02/23.html#P49
# Rewritten to use osascript args -> run handler args.
# Added ability to pass additional initial command and args to new shell.
#    Bug: Non ASCII characters are unreliable on Tiger.
#         Tiger's osascript seems to expect args to be encoded in
#         the system's primary encoding (e.g. MacRoman).
#         Once in AppleScript, they are handled OK. Terminal sends them
#         back to the shell as UTF-8.

test $# -eq 0 && set -- : # default command if none given
osascript - "$(pwd)" "$@" <<\EOF
on run args
  set dir to quoted form of (first item of args)
  set cmd_strs to {}
  repeat with cmd_str in rest of args
    set end of cmd_strs to quoted form of cmd_str
  end
  set text item delimiters to " "
  set cmd to cmd_strs as Unicode text
  tell app "Terminal" to do script "cd " & dir & " && " & cmd
end
EOF

Example: tfork git log -p ..FETCH_HEAD


Amendment: cwd of an already running process “occupying” a Terminal tab

The idea of “the current directory of the program occupying the current tab” is not as obvious as one might expect.

Each Terminal tab has a single tty device that is used by the processes it runs (initially, a shell; thereafter, whatever the shell starts).

Each (normal) Terminal tty has a single foreground process group that one might consider as “occupying” the tty.

Each process group can have multiple processes in it.

Each process can have its own current working directory (cwd) (some environments give each thread their own cwd or cwd-equivalent, but we will ignore that).

The preceding facts establish a kind of trail that from tty to cwd: tty -> foreground process group -> processes of the foreground process group -> cwds.

The first part (from tty to foreground processes) of the problem can be solved with the output from ps:

ps -o tty,pid,tpgid,pgid,state,command | awk 'BEGIN{t=ARGV[1];ARGC=1} $1==t && $3==$4 {print $2}' ttyp6

(where “ttyp6” is the name of the tty of interest)

The mapping from process (PID) to cwd can be made with lsof:

lsof -F 0n -a -p 2515,2516 -d cwd

(where “2515,2516” is a comma-separated list of the processes of interest)

But under Tiger, I see no direct way to get the tty device name of a particular Terminal window. There is a horribly ugly way of getting the tty name in Tiger. Maybe Leopard or Snow Leopard can do better.

I put it all together in an AppleScript like this:

on run
    (* Find the tty. *)
    -- This is ugly. But is seems to work on Tiger. Maybe newer releases can do better.
    tell application "Terminal"
        set w to window 1
        tell w
            set origName to name
            set title displays device name to not title displays device name
            set newName to name
            set title displays device name to not title displays device name
        end tell
    end tell
    set tty to extractTTY(origName, newName)
    if tty is "" then
        display dialog "Could not find the tty for of the current Terminal window." buttons "Cancel" cancel button "Cancel" default button "Cancel"
    end if

    (* Find the PIDs of the processes in the foreground process group on that tty. *)
    set pids to paragraphs of (do shell script "
ps -o pid,tty,tpgid,pgid,state,command |
awk '
    BEGIN   {t=ARGV[1];ARGC=1}
    $2==t && $3==$4 {print $1}
' " & quoted form of tty)
    if pids is {} or pids is {""} then
        display dialog "Could not find the processes for " & tty & "." buttons "Cancel" cancel button "Cancel" default button "Cancel"
    end if

    (* Find the unique cwds of those processes. *)
    set text item delimiters to {","}
    set lsof to do shell script "lsof -F 0n -a -d cwd -p " & quoted form of (pids as Unicode text) without altering line endings
    set text item delimiters to {(ASCII character 0) & (ASCII character 10)}
    set cwds to {}
    repeat with lsofItem in text items of lsof
        if lsofItem starts with "n" then
            set cwd to text 2 through end of lsofItem
            if cwds does not contain cwd then ¬
                set end of cwds to cwd
        end if
    end repeat
    if cwds is {} then
        display dialog "No cwds found!?" buttons "Cancel" cancel button "Cancel" default button "Cancel"
    end if
    if length of cwds is greater than 1 then
        set cwds to choose from list cwds with title "Multiple Distinct CWDs" with prompt "Choose the directory to use:" without multiple selections allowed and empty selection allowed
        if cwds is false then error number -128 -- cancel
    end if

    (* Open a new Terminal. *)
    tell application "Terminal" to do script "cd " & quoted form of item 1 of cwds
end run

to extractTTY(a, b)
    set str to textLeftAfterRemovingMatchingHeadAndTail(a, b)
    set offs to offset of "tty" in str
    if offs > 0 then
        return text offs through (offs + 4) of str
    end if
    return ""
end extractTTY
to textLeftAfterRemovingMatchingHeadAndTail(big, little)
    set text item delimiters to space
    if class of big is not list then set big to text items of big
    if class of little is not list then set little to text items of little
    set {maxLen, minLen} to {length of big, length of little}
    if maxLen < minLen then ¬
        set {big, little, maxLen, minLen} to {little, big, minLen, maxLen}

    set start to missing value
    repeat with i from 1 to minLen
        if item i of big is not equal to item i of little then
            set start to i
            exit repeat
        end if
    end repeat
    if start is missing value then
        if maxLen is equal to minLen then
            return ""
        else
            return items (minLen + 1) through end of big as Unicode text
        end if
    end if

    set finish to missing value
    repeat with i from -1 to -minLen by -1
        if item i of big is not equal to item i of little then
            set finish to i
            exit repeat
        end if
    end repeat
    if finish is missing value then set finish to -(minLen + 1)

    return items start through finish of big as Unicode text
end textLeftAfterRemovingMatchingHeadAndTail

Save it with Script Editor (AppleScript Editor in Snow Leopard) and use a launcher (e.g. FastScripts) to assign it to a key (or just run it from the AppleScript menu (enabled via /Applications/AppleScript/AppleScript Utility.app)).