How to Automatically Set Terminal Title to Directory Name

bashcommand linetitlebar

Currently, my bash terminal/tab title is set based on the directory I'm in. For example:


This isn't very useful if I have multiple tabs open side-by-side. For example, if I have 4 tabs of the above dir open side-by-side, all I see is


4 times.

I'd like all my terminal titles to be set automatically to just the last part of the path. In the example above, I'd like the title to be


Obviously, the title should change when I change directories. I'd like to do this without changing my prompt, so the prompt and the terminal title should be different.

Is there a way to do this?

Best Answer

Why do you want to do it without modifying your PS1 variable? That is the correct way to do it.

If you run the following, you'll get what you want:

export PS1="\[\e]0;\W\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "

This is just taking the default prompt:

export PS1="\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "

... and replacing \u@\h: \w with \W.

You can do the same thing with any command that echoes the right escape code:

echo -en "\e]0;${PWD##*/}\a"

... but then you'd be constantly fighting bash to stop it from doing it using PS1 (the best way).