Opening specified path in Terminal’s new tab

24 Mar 2009

If you ever wondered how to open specified path in new tab of Terminal.app or reuse current one if it is not busy (running a command), here’s a script you may use:

tell application "Terminal"

    activate

    set windowCount to (count of the windows)

    -- Terminal may be just launched loading the shell, wait a bit
    if windowCount is greater than 0 and first window is busy then
        delay 0.5
    end

    -- Still busy / no windows? open new tab
    if windowCount is greater than 0 and first window is busy or windowCount is 0 then
        tell application "System Events" to tell process "Terminal"
            click first menu item of first menu of second menu item of first menu of third menu bar item of first menu bar
        end tell
    end if

    do script "cd #{e_as(e_sh(dir))}" in first window

end tell

Where #{e_as(e_sh(dir))} is your desired folder. This is modified chunk of TextMate‘s command script found at Mark Eli Kalderon’s Blog. Thanks Mark!

Note: Mark’s TextMate command script does not open anything when Terminal.app has no windows or it is not running.

Update

It uses now click menu instead of keystroke “System Events” command, because in some cases when you had this script assigned to shortcut that used Ctrl or Shift modifiers, those modifiers were sent together with Cmd to “Terminal” producing invalid behavior.

It waits 0.5 second when window is busy just in case Terminal.app was not running and it is just loading the shell which makes it busy for short while too. Fixes incorrect behavior of opening extra tab when Terminal.app was not running.

Posted in AppleScript, Mac, Programming