Display command in xterm titlebar

Basically, you need:

trap 'printf "\033]0;%s\007" "${BASH_COMMAND//[^[:print:]]/}"' DEBUG

at the end of your .bashrc or similar. Took me a while to work this out -- see my answer here for more information :)


(Inspired by this SU answer)

You can combine a couple bash tricks:

  • If you trap a DEBUG signal, the handler is called before each command is executed
  • The variable $BASH_COMMAND holds the currently executing command

So, trap DEBUG and have the handler set the title to $BASH_COMMAND:

trap 'printf "\033]0;%s\007" "${BASH_COMMAND//[^[:print:]]/}" >&2' DEBUG

This will keep the title changed until something else changes it, but as long as your $PS1 stays the same it won't be a problem -- you start a command, the DEBUG handler changes the titlebar, and when the command finishes bash draws a new prompt and resets your titlebar again.

A useful tip found here (also where that SU answer came from) is to include:

set -o functrace

This will make bash propagate the DEBUG trap to any subshells you start; otherwise the titlebar won't be changed in them


I worked around my own solution from various posts around. This creates a title containing user, hostname, pwd, tty and currently executed command (for bash).

This looks like this (no command being executed):

.:[user@hostname:/home/user][pts/10]:.

And like this (executing a command):

.:[user@hostname:/home/user][pts/10] {tail -F /var/log/syslog}:.

Somewhere in the .bashrc, i extended PS1:

# set the terminals title. This is the "post-command" part,
# need to use a trap for pre-command (to add the command line to the title)
PS1+="\[\033]2;.:[\u@\h:\$PWD] [$(tty | cut -b 6-)]:.\007\]"

Adds the current command, using history 1 and trap:

# set a fancy title (this is pre-command, in PS1 is after-command (to reset command)
trap 'echo -ne "\033]2;.:[${USER}@${HOSTNAME}:${PWD}] [$(tty | cut -b 6-)] {$(history 1 | sed "s/^[ ]*[0-9]*[ ]*//g")}:.\007"' DEBUG

Feel free to adopt to your needs.