how can I set my bash window title to the last command that ran?

I'd like the title of my terminal windows to show the last command that ran. It'd be handy for finding the terminal that's running Mongrel in Dev/Test/Prod etc (for testing rails apps).

I tried this code:

if [ "$SHELL" = '/bin/bash' ]
then
    case $TERM in
         rxvt|*term)
            set -o functrace
            trap 'echo -ne "\e]0;$BASH_COMMAND\007"' DEBUG
            #  export PS1="\e]0;$TERM\007$PS1"
         ;;
    esac
fi

At least, I think that's the code that I tried. It did work, but it caused some strange behavior, like window titles that would get stuck in a loop until I hit Ctrl C when changing directory to a symlink.

What's a reliable way to set my window title to the last command that was run?


Solution 1:

You can also use the xtitle tool:

sudo apt-get install xtitle
lastcmd() { xtitle $(history 1 | cut -c8-); }
PROMPT_COMMAND=lastcmd

Solution 2:

Using only standard commands

lastcmd() { LASTCMD=$(history 1 | cut -c8-); echo -ne "\e]2;$LASTCMD\a\e]1;$LASTCMD\a"; }
PROMPT_COMMAND=lastcmd

Test it

echo 'This echo command should be displayed on my window title'

Timestamp

To also display the time of the last command, set the environment variable HISTTIMEFORMAT:

HISTTIMEFORMAT=%c

See man date for a complete list of date/time formats.

To disable the timestamp prefix on window title:

unset HISTTIMEFORMAT

Persistence

A good place to put these two lines is in your ~/.bashrc