Bash – How to make tmux tell bash to display the *logical* version of the current directory in newly opened windows

bashcd-commandtmux

Background

I'm using tmux 2.0, Ubuntu 14.04.2 LTS in VirtualBox.

In order to make tmux open new windows with the same path as the current window I added this line to my ~/.tmux.conf file:

bind c new-window -c "#{pane_current_path}"

Note that in tmux, if I cd from home to a subdirectory via a symlink, then check pwd and pwd -P I get:

~$ cd pythons
~/pythons$               # An awesome prompt

~/pythons$ pwd           # According to "man pwd" this shows the "logical" path
/home/qiime/pythons

~/pythons$ pwd -P        # and this shows the "physical" path
/media/sf_Google_Drive/Home/Programs/Pythons

The problem is

If I open a new tmux window while in ~/pythons the new bash prompt takes on the physical path:

/media/sf_Google_Drive/Home/Programs/Pythons$     # Not an awesome prompt

Q: Yes, it's opened to the correct directory… but is there a way to get tmux to start bash with the logical path instead of the full-blown physical path?

Alternatively, perhaps there is something I can add to .bashrc to make this happen?

Edit:

To check if any config settings are causing this issue I tried commenting out all lines in ~/.tmux.conf except for

bind c new-window -c "#{pane_current_path}"

but I still get the full physical path. I also tried echoing the current (logical) path from the top of my ~/.bashrc file. Unfortunately, this echos the ugly physical path of the parent window, which apparently has become the new window's physical and logical path. So tmux 2.0 must be passing it to the new bash instance via the value of "#{pane_current_path}"

Moreover, I just found this recently opened tmux issue: pane_current_path doesn't agree with pane's PWD #33 indicating that this behavior originates in tmux code.

Q: So maybe my question should be, Is there a workaround?

Best Answer

The following worked for me.

To ~/.bashrc, add the line:

PS1='$([ -n "$TMUX" ] && tmux setenv TMUXPWD_$(tmux display -p "#I") $PWD)\u@\H:\w$ '

And to ~/.tmux.conf, add the lines:

bind-key c run-shell 'tmux neww "cd $(tmux display -p "\$TMUXPWD_#I"); exec bash"'
bind-key % run-shell 'tmux splitw -h "cd $(tmux display -p "\$TMUXPWD_#I"); exec bash"'
bind-key '"' run-shell 'tmux splitw -v "cd $(tmux display -p "\$TMUXPWD_#I"); exec bash"'

Restart tmux.

Sources

See the section, "How can I open a new window in the same directory as the current window?" at http://tmux.svn.sourceforge.net/viewvc/tmux/trunk/FAQ.

Note that the characters at the end of the .bashrc line had to be changed from the original at the link above to '\u@\H:\w$ ' in order to properly display the complete bash prompt. See http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/bash-prompt-escape-sequences.html for more info.

Related Question