Strovent SystemsSign in
Reference

Do all terminals understand ANSI escape codes? TERM, terminfo and dumb terminals

Not every terminal supports every escape code, and output can go to a file or a dumb terminal. Why, and how tput and terminfo pick the right codes.

The "ANSI" codes people mean, such as ESC [ 31 m for red, come from the ECMA-48 standard (ISO/IEC 6429), plus extensions that xterm made common. Many terminal programs understand the common ones. Whether it is safe to print them depends on what is at the other end.

Three cases where hard-coded codes go wrong

  1. The terminal does not support the feature. ECMA-48 defines many control functions, and a terminal implements some of them. A VT100, for example, has no color: its terminfo entry has no setaf capability, so TERM=vt100 tput setaf 1 prints nothing.
  2. There is no real terminal. TERM=dumb is the terminfo entry "80-column dumb tty": it can ring the bell, return the carriage and move down a line, and nothing else.
  3. The output is not a terminal at all. When output goes to a file or a pipe, the codes are written as bytes and show up as ^[[31m in the file. Programs avoid this by checking where their output goes: for example, ls --color=auto emits color codes only when standard output is connected to a terminal.

Terminals also have no standard way to tell a program which features they support. Instead, the TERM variable names an entry in the terminfo database, which lists the capabilities of that terminal type. See TERM and terminfo.

Use terminfo through tput

tput looks up the capability for the current TERM and prints the right sequence, or nothing if the terminal does not have it:

red=$(tput setaf 1) reset=$(tput sgr0)
printf '%sError%s\n' "$red" "$reset"
tput colors        # 8, 256, or -1 when TERM has no colors

If TERM names a type the host does not know, tput reports an unknown terminal and prints no sequence. See Unknown terminal type or "Error opening terminal" when you use tmux, screen or SSH.

What a missing feature looks like

Sources

Spotted a mistake? Email [email protected].