Linux: How to make a terminal window title reflect the current path

Updated . Posted . Visible to the public. Repeats.

By default, your terminal emulator (Gnome Terminal, Terminator, etc.) sets some kind of window title to reflect the shell type you are running (e.g. /bin/bash).
This is most often not too helpful, but you can change that from your shell.

To set a specific title, print an escape sequence like this:

echo -en "\033]0;Hello\a"

You can easily include the current path:

echo -en "\033]0;$(pwd)\a"

Or, to replace your home directory's part with a tilde:

echo -en "\033]0;$(pwd | sed -e "s;^$HOME;~;")\a"

Or, to only show the directory name without a path:

echo -en "\033]0;$(basename `pwd`)\a"

Bash

To make your Bash automatically update your window title whenever you switch directories, simply specify a PROMPT_COMMAND environment variable.

set-window-title() {
  echo -en "\033]0;$(pwd | sed -e "s;^$HOME;~;")\a"
}

if [[ "$PROMPT_COMMAND" ]]; then
  export PROMPT_COMMAND="$PROMPT_COMMAND;set-window-title"
else
  export PROMPT_COMMAND=set-window-title
fi

You may put that into your ~/.bashrc to persist and automatically activate when you open a new terminal window.

ZSH

To make your Bash automatically update your window title whenever you switch directories, add the following line to your precmd function in the ~/.zshrc. In case your are using oh-my-zsh you need to set DISABLE_AUTO_TITLE="true".

function precmd () {
  echo -ne "\033]0;$(pwd | sed -e "s;^$HOME;~;")\a"
}

Demo video

Arne Hartherz
Last edit
Arne Hartherz
Attachments
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2021-01-27 09:47)