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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)