gnome-terminal: how to preserve symlinks of working directory when opening new tab?

This bug is being tracked on Ubuntu Launchpad and GNOME Bugzilla.

Since this mainly annoys me with only a few directories, I use the following simpler workaround.

Suppose you have /home/username/work as a symlink to /long/path/named/asdf. So you do cd ~/work in gnome-terminal, open a new tab, and find terminal reporting the full path. To fix this, just put the following in your .bashrc:

cd ${PWD/\/long\/path\/named\/asdf/$HOME\/work}

When gnome-terminal starts a new shell, it gets the current directory with $PWD, and if it contains /long/path/named/asdf, it replaces that string with $HOME/work, and cds to the resulting string. If $PWD does not contain the string, it is equivalent to cd $PWD, which does nothing.


I suspect there is no truly good answer to this. gnome-terminal finds bash's current working directory by inspecting /proc/<pid>/cwd, which has the symlinks expanded (probably for security reasons, if nothing else). I don't know of another way for one process to find another process's working directory.

As a workaround, there are some bash tricks you could try, but see the WARNING below! In .bashrc:

...
PROMPT_COMMAND='pwd >~/.bashlocal_saved_dir'
...

[ -n "$PS1" -a -f ~/.bashlocal_saved_dir ] && cd `cat ~/.bashlocal_saved_dir`
# end of .bashrc

This will do two things. First, every time bash displays the prompt, it will first write its current working directory into the file .bashlocal_saved_dir in your home directory. Second, when bash starts interactively (as opposed to running a script), it will change to the directory stored in that same file. This means that when you start a new interactive bash, it will start in the same dir as the bash that last displayed its prompt. Note that you can hit Enter to cause a bash to redisplay its prompt, thus making it the last. :)

WARNING: This is a hack, and I have only tried it up to the point that I know it works. Think bubble gum and shoestrings. It may have surprising effects, and will certainly not work as cleanly as gnome-terminal's approach. In particular, if you're running a lot of tabs at once, all doing background tasks, you may very well end up in the "wrong" directory when opening a new tab.