#!/bin/blog --author=p4bl0

the blog where all numbers are written in base 10

Fast window switching: Bash tricks

by p4bl0, on
last update by p4bl0, on

As a follow up to Fast window switching, I'm gonna present here a few Bash tricks to have terminal windows title as useful as possible.

Let's list what informations we want:

  • user name,
  • host name,
  • working directory path,
  • currently running command,
  • a possibility to desambiguate two similar titles if we need to.

To have those informations in the title we use special Bash escape control character in the PS1 environment variable. The PS1 variable is evaluated after each command is executed and the result of its expansion is used as your prompt.


This line of code in your .bashrc (after you set your usual PS1 value) will make your terminal windows title look like "username@hostname:/working/directory".

We also said we'd like to have the current command in our windows title. The problem is that as I said before, the evaluation of this variable takes place after the command is executed in order to display your prompt again, and it's not very interesting to have the last command you used in the title. We need to have it while the command is running to be able to easily fast switch to terminals running editors, mail readers or REPL (programming languages, databases...) for instance.

The solution here is a dirty hack: we trap the DEBUG Bash signal and call a function which set the title we want:

function___set_title () {
  local WD=$(pwd | sed "s/^\/home\/$USER/~/")
  echo -ne "\e]0;$USER@$HOSTNAME:$WD ($1)\a"
trap '___set_title "$BASH_COMMAND"' DEBUG

These lines in your .bashrc will make your terminal windows title look like "username@hostname:/working/directory (currently running command)".

That's already very good, but you still may have two terminal windows with the same title. So we need a way to name our windows with a name we can randomly choose. To acheive this we simply get the ___set_title function and PS1 to put a specific variable at the beginning of the title. And we write a little Bash function that will set this variable value for the current session.

Here is the resulting code:

export LOCALNAME=""
function termname () { export LOCALNAME="$1|"; }
function ___set_title () {
  local WD=$(pwd | sed "s/^\/home\/$USER/~/")
  echo -ne "\e]0;${LOCALNAME}$USER@$HOSTNAME:$WD ($1)\a"
trap '___set_title "$BASH_COMMAND"' DEBUG

And this enable you to name your windows using the termname command with the name you decide as argument. Your window's title will then look like "name|username@hostname:/working/directory (currently running command)" (or without the running command if there's not one).

Don't forget to also set this up in hosts where you frequently ssh to so the username and hostname in the title are useful for real :-p.

If you have any remark about this blog or if you want to react to this article feel free to send me an email at "pablo <r@uzy dot me>".