Hacking by Walkingice: tmux split window in current directory


tmux split window in current directory

I use tmux to instead of gnu-screen due to tmux supports vertical window splitting.

There are many common question such as 'How to create a new window in the current directory'. Here are some simple how-to, inspired by tmux FAQ.

1. Preparing - set environment variable by PS1 in shell
add this line to your .bashrc
PS1='$([ -n "$TMUX" ] && tmux setenv TMUXPWD_$(tmux display -p "#I") $PWD)${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '

How it works?

$([ -n "$TMUX" ] && tmux setenv TMUXPWD_$(tmux display -p "#I") $PWD)
The previous half part makes the magic, #I indicates the index of each displays. In display 1, it saves current directory ($PWD) into environment variable $TMUXPWD_1, corresponding to $TMUXPWD_2, $TMUXPWD_3 ...etc.

Just type 'printenv |grep TMUXPWD' and you will know everything.

Well, this is my own prompt (such as walkingice@my_laptop$ ), you can keep your own settings by 'cat ~/.bashrc |grep PS1'

2. Create new window in current directory
Follow the common FAQ, add this line to your .tmux.conf
bind-key c run-shell 'tmux neww "cd $(tmux display -p "\$TMUXPWD_#I"); exec bash"'
3. Split window in current directory
Since we did the magic to PS1, why don't we keep using it? Add these two lines to your .tmux.conf
bind-key h run-shell 'tmux splitw -v "cd $(tmux display -p "\$TMUXPWD_#I"); exec bash"'
bind-key v run-shell 'tmux splitw -h "cd $(tmux display -p "\$TMUXPWD_#I"); exec bash"'
Caution: I prefer Ctrl-a h to split horizontal window(splitw -v). In other words, when I click Ctrl-a h, I am saying "Hey, give me a horizontal line". I think it make more sense than tmux original key binding.


  1. bind h splitw -h "cd $PWD; exec $SHELL"
    bind v splitw -v "cd $PWD; exec $SHELL"

    are far simpler imho — plus they work with the CWD of the individual pane, thus are not limited to the pane that lastly set $TMUXPWD_#I. (If there was no prior shell to set $PWD in that pane, e. g. as an app was started directly, cd will default to ~.)

    Thanks for the hints, anyway.

  2. Silly me, I completely ignored that tmux doesn't look at the individual $PWD. My bad.

  3. Recent tmux (any version after 2011), there are format option like pane_pid, and later (2012.4) there is pane_current_path. So for most use cases, these two will be sufficient.

    Use: tmux display -p "#{pane_current_path}"

    in a script.