void-pointer
void-pointer

Reputation: 14827

iTerm2 and tmux: open new tab in working directory of current tab

When I open a new tab (via ⌘T) on a remote shell using iTerm2 and tmux, I almost always want the new tab to have the same working directory as the current tab. The best I can do is make iTerm2 open up the new tab in the same directory in which I ran tmux -CC or tmux -CC attach. (This behavior can be configured by navigating to Preferences → Profiles → General → Working Directory.)

This directory will not necessarily be the working directory of the current tab. Is there any way to get the behavior I'm looking for? I searched online for a while but could not find any helpful information.

Upvotes: 9

Views: 5247

Answers (4)

Paul Dulaney
Paul Dulaney

Reputation: 121

I don't know if my solution was available when the question was originally asked (2015), but here is a very simple solution in iTerm2 in 2025:

Session> Duplicate Session

This will create a new tab in the same directory. If (like me) you prefer a new window, right-click on the new tab and select "Move to New Window".

Upvotes: 0

Parker Tailor
Parker Tailor

Reputation: 1485

When using Iterm2, if you want a new tab to open in the same directory as the current tab via ⌘T, there is an option available in your profile under preferences.

From the iTerm2 main menu:

Iterm2 -> Preferences -> Profiles -> General -> Working Directory -> Reuse previous session's directory

Upvotes: 17

Kevin Powell
Kevin Powell

Reputation: 601

With tmux, one solution is to set alias itab='open . -a iterm' in your .bash_alias.

Upvotes: 0

RyanMacG
RyanMacG

Reputation: 339

If you're using ZSH you could try something like this;

function tab() {
  local command="cd \\\"$PWD\\\"; clear; "
  (( $# > 0 )) && command="${command}; $*"
}

If you're using bash I'm not sure what the equivalent would be. Also if you're using prezto or Oh-My-ZSH the tab function is already built in.

UPDATE

Having had a look at how prezto does it, this should be the full solution

local command="cd \\\"$PWD\\\""
(( $# > 0 )) && command="${command}; $*"

the_app=$(
  osascript 2>/dev/null <<EOF
    tell application "System Events"
      name of first item of (every process whose frontmost is true)
    end tell
EOF
)

[[ "$the_app" == 'iTerm' ]] && {
  osascript 2>/dev/null <<EOF
    tell application "iTerm"
      set current_terminal to current terminal
      tell current_terminal
        launch session "Default Session"
        set current_session to current session
        tell current_session
          write text "${command}"
        end tell
      end tell
    end tell
EOF
}

It uses the CLI for AppleScript and seems to work fine for me.

Upvotes: 0

Related Questions