ITerm2 and tmux: open a new tab in the working directory of the 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 get iTerm2 to open a new tab in the same directory in which I ran tmux -CCor tmux -CC attach. (This behavior can be configured by going to Settings → Profiles → General → Working Directory.)

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

+5
source share
3 answers

when using Iterm2, if you want the new tab to open in the same directory as the current tab with ⌘T, in the settings in the settings you can select the option in the settings.

In the main menu of iTerm2:

Iterm2 -> Preferences -> profiles -> working directory -> Reuse Previous Session Directory

+7
source

If you use ZSH, you can try something like this:

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

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

UPDATE

Seeing how it works, this should be the complete 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 just fine for me.

0
source

tmux - alias itab='open. -a iterm' alias itab='open. -a iterm' .bash_alias.

0

All Articles