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
- 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
setafcapability, soTERM=vt100 tput setaf 1prints nothing. - There is no real terminal.
TERM=dumbis the terminfo entry "80-column dumb tty": it can ring the bell, return the carriage and move down a line, and nothing else. - 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
^[[31min the file. Programs avoid this by checking where their output goes: for example,ls --color=autoemits 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
- A code the terminal does not handle can do nothing, or leave stray characters such as
[31mon the screen. - With the wrong
TERM, full-screen programs draw in the wrong place or leave rubbish behind. See Fix a terminal full of garbage after printing a binary file.
Related
- Escape sequences
- TERM and terminfo
- Colors: 16, 256 and true color
- Unknown terminal type or "Error opening terminal" when you use tmux, screen or SSH
- less shows ESC[31m instead of colors: less -R and --color=always
- tput "No value for $TERM and no -T specified" and "TERM environment variable not set"