lostwebsite.net blog

Annex to the Lost Website

Automatically set terminal title in X

with 2 comments

I’ve been using the Mercurial Shell Prompt hack for a while until I got annoyed at it. It caused a Python interpeter to start at every prompt, which is expansize especially if your system is already under strain.

This new shell hack is a lot faster much more generic. This small snippet is used to dynamically set the title of the terminal window in the following situation:

  • if the terminal is at the prompt, set the title of the window to the name of the current directory
  • if a program is running, set the title of the window to the name of the running program

The code is pretty straightforward. It uses prompt expansion and a magical escape sequence which is understood by the terminal.

case $TERM in
    xterm*)
        precmd () {print -Pn "\e]0;%1~\a"}
        preexec () {print -n "\e]0;$1\a"}
        ;;
esac

This is for Zsh. See this page for how to do the same with Bash and other shells.

There are a lot of variants you can make in the format of the title. Check your shell manual for more information.

If you use Konsole or GNOME Terminal, make sure they are configured to actually use what the emulated terminal dumps. Konsole has an option to set the terminal name to what you want so I suppose the GNOME Terminal has a similar feature.

As usual, I’m not claiming I’ve invented this. I probably read this on a blog somewhere, but I don’t remember where. This is too bad for me because I missing on possible pingbacks. Kudos to whoever I’ve picked this from.

Zsh manual links

Written by fdgonthier

May 15, 2009 at 12:00 pm

2 Responses

Subscribe to comments with RSS.

  1. It is probably a bad idea to redefine precmd like this. I have various things that are done as precmd (autojump, battery checking) so I prefer to use the syntax
    precmd_functions+=myfunction
    For the title setting, I don’t use the current program thingy, hence I only change it at each cd. So in fact, it is
    chpwd_functions+=myfunction
    where myfunction contains the “case” (including cases for screen and *xvt).
    Not invented by me either ;)

    milosh

    November 3, 2009 at 12:47 pm

  2. Thanks for that insight. I only have this scriptlet running but I understand why you would do that like you suggest.

    fdgonthier

    November 3, 2009 at 2:01 pm


Leave a Reply