Automatic $TERM selection

Everybody wants to use the terminal description that best fits their terminal, but the most flexible and powerful terminal descriptions are also the rarest - which means terminal emulators tend to default to the oldest and most widespread terminal descriptions even if they fall far short of what the emulator can actually do.

Here's a fragment of .bashrc that I use to automatically set $TERM to the most capable version available when I log in:

case "$TERM" in
    xterm*)
        TERMLIST=(
            xterm-256color
            xterm-16color
            xterm-color
            xterm
            ) ;;
    screen*)
        TERMLIST=(
            screen-256color-bce
            screen-256color
            screen-16color-bce
            screen-16color
            screen
            ) ;;
    *)
        TERMLIST="$TERM" ;;
esac
for term in $TERMLIST; do
    infocmp "$term" >/dev/null 2>&1 &&
        export TERM=$term &&
        break
done

Basically, it says:

  • If you currently claim to be an xterm variant, here's a list of alternatives from most to least powerful.
  • If you currently claim to be a GNU Screen variant, here's a list of alternatives from most to least powerful.
  • If you currently claim to be something else, we don't have any alternatives so stick with what you've got.
  • For each alternative:
    • Ask infocmp (part of the ncurses tools) if it can find a terminal definition with that name.
    • If it can, we assume other tools will be able to find it too, and we set $TERM appropriately and stop looking.

Note that $TERMLIST for xterm* and screen* uses the bash/zsh array syntax. If you're using a different shell, changing the parentheses to ordinary double-quote characters should work just as well (but doesn't work in zsh).

changed October 31, 2009