5

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?

1

You can also use the xtitle tool:

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

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

  • So I'd put this in my .bashrc, correct? – jcollum Jan 17 '12 at 17:14
  • Nope, I added that to my bashrc and started a new terminal and I got this at my prompt: ]0;echo -ne ""]2;reload]1;reload~> and my window title is cut -c8-. That's what it looks like when I start the terminal. Sorry, that didn't work. – jcollum Jan 17 '12 at 17:18
  • Correct: ~/.bashrc is a good place to put that. Hummm... this works fine for me on Lubuntu10.10/bash at home and on my PuTTY/bash at work. Please can you provide a portion of your ~/.bashrc and $PS1, $PS2, $PS3 and $PS4? (you can edit your question). Then, I can test on my computer. Cheers. – olibre Jan 17 '12 at 21:43
  • @jcollum I can test on my computer, but I need to be as close as possible to your environement. Therefore, please provide some info as your .bashrc and PSx variables. Cheers. – olibre Jan 18 '12 at 21:11
  • @olibre I have this working for local terminals, is there a way to use this with remote ssh connections too? While i am working on a remote dev server I often tail the error logs but there are several log files, I want to be able to see which file im tailing in the title bar. – Chris Nov 11 '17 at 15:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.