Read more

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

Arne Hartherz
January 27, 2021Software engineer at makandra GmbH

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.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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

Posted by Arne Hartherz to makandra dev (2021-01-27 10:47)