Putting the current directory in your terminal's titlebar on Linux & Cygwin

Having the current directory in your terminal's title bar has a number of advantages. If, like me, you have a lot (more than 5) of terminals open at any time, each in a different directory for a different project, you'll probably have to try several times before finding the correct window.

Most of this can easily be solved by adding a single line of code to your ~/.bashrc file. Let's see what that line of code is:

PROMPT_COMMAND="echo -ne \"\033]0;\$(pwd | sed "s#^$HOME#~#g")\007\""
There's a few things going on here so I'll about them one by one.

First of all, notice how I'm setting the PROMT_COMMAND bash variable. The contents of this variable are executed just after the command is executed and just before bash prints it's next prompt.

The command that's executed before every prompt, echo's a very special string. At the start of this string is an incantation that tells your terminal emulator to use the following text as the window title.

We'd like the current directory (given by the pwd command) to be shown, but if we're in a subdirectory of our home directory, we don't like to see the current path in it's rough, expanded form (/cygdrive/c/Users/Ives/Desktop/cyghome on my computer). Because of this, we're filtering it through sed and replacing this long string with ~ (note that because of the way sed works, this might not work if you have characters except for letters, digits and forward slashes in your home directory).

This should work on recent versions of bash and on most terminal emulators (this includes PuTTY and the Cygwin bash.exe).

No comments:

Post a Comment