Terminal – How and Where is $TERM Interpreted?

consoleterminal

I'm wondering how some terminal magic works internally.

While playing around with docker containers, the environment variable $TERM was not set. This led to strange-looking console applications like vim and tmux, but also to CTRL+l (clear screen) being ignored.

I'm pretty sure that all feature like partial screen updates, colors, commands like screen reset etc. are realized using escape codes, right?

So where is this variable interpreted and allows for example resetting my terminal screen using CTRL+l if I set the right value there? Who checks for example which colors are supported (xterm vs xterm-256color)? The shell? The application or a library like ncurses? And where are the possible values / terminal types defined?

Best Answer

$TERM is read and interpreted by the terminfo system. terminfo also refers to the database of terminal descriptions which you can find on most systems in /usr/share/terminfo. $TERM must match one of the entries in that database. There was also an older library called termcap which had fewer capabilities, but terminfo has replaced it. In modern systems, terminfo is part of the ncurses library.

Applications usually either fetch terminal capabilities directly using library functions like tigetstr() or they use higher level curses interfaces to manage the layout of the screen. Either way, $TERM and the terminfo database will be consulted.