Show running command as title in gnome-terminal

I’ve happily been running debian stable with gnome 43. I’m using the normal gnome-terminal that I generally open with ctrl+alt+t. It’s a hotkey i’ve configured in the gnome-settings. Having a hotkey makes it super quick to open a terminal, but that means i get a lot of them. By default they all of the same title, which is not great. It would be great if (like tmux) the window title would show the current running program.

To do that, i’ve modified my .bashrc with the following:

1
trap 'echo -ne "\033]2;$(history 1 | cut -c 28-)\007"' DEBUG

What does this do?

The trap command allows you to capture signals. There’s no man page so just use trap --help to get the gist of it. It will execute echo -ne "\033]2;$(history 1 | cut -c 28-)\007" when a signal is captured. The DEBUG at the end of the line tells trap that it should run it just before the signal.

The echo with the \033]2; pushes it to the title of the terminal. It needs to be terminated with \007. So everything between that becomes the title of the gnome-terminal. The $(history 1 | cut -c 28-) takes the last item from the history and then cuts of the first 28 characters. The 28 characters is becaues i use HISTTIMEFORMAT="%Y-%m-%dT%H:%M:%S ", which makes the history have a date/time with it. That, together with HISTSIZE means i need to cut after the first 28 characters, but this might differ for you.