Make gnome-terminal show the command running as title [duplicate]

This is a more complete solution actually taking care of bash-completion spamming garbage.

To be clear: I did nothing on my own here but research. All credit goes to Marius Gedminas.

This works perfectly for me with Gnome-Terminal/Terminator (put it in your .bashrc or somewhere that's getting sourced)

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"'

    # Show the currently running command in the terminal title:
    # http://www.davidpashley.com/articles/xterm-titles-with-bash.html
    show_command_in_title_bar()
    {
        case "$BASH_COMMAND" in
            *\033]0*)
                # The command is trying to set the title bar as well;
                # this is most likely the execution of $PROMPT_COMMAND.
                # In any case nested escapes confuse the terminal, so don't
                # output them.
                ;;
            *)
                echo -ne "\033]0;${USER}@${HOSTNAME}: ${BASH_COMMAND}\007"
                ;;
        esac
    }
    trap show_command_in_title_bar DEBUG
    ;;
*)
    ;;
esac

Also this is a cross-post because I just found out about it and wanted to share and I think it's useful here as well.


This has been sort of answered here.

  • trap 'command' DEBUG makes bash run command before every command.
  • echo -ne "\033]0;Title\007" changes the title to "Title"
  • $BASH_COMMAND contains the command being run.

Combining these we get

trap 'echo -ne "\033]0;$BASH_COMMAND\007" > /dev/stderr' DEBUG

Then we just have to reset the title after we complete the command. I did this by setting $PS1 to change the title to the current path.

tl;dr: Add these two lines (in this order, otherwise I got a garbled prompt) to the bottom of ~/.bashrc

PS1="\033]0;\w\007${PS1}"
trap 'echo -ne "\033]0;$BASH_COMMAND\007" > /dev/stderr' DEBUG

Edit: Your $PS1 might already change the title, in which case only the last line is needed.