A Linux terminal has a lot more features than the TeleType of yore. On a TeleType, text spews out and scrolls up and is gone forever. A real terminal can use escape characters to do navigate around and emulate most of what you like about GUIs. However, doing this at the lowest level is a chore and limits portability. Luckily, all the hard work has already been done.

First, there’s a large database of terminal capabilities available for you to use: terminfo. And in addition, there’s a high-level library called curses or ncurses that simplifies writing programs to control the terminal display. Digging deep into every nook and cranny of ncurses could take years. Instead, I’m going to talk about using a program that comes with ncurses to control the terminal, called tput. Using these two commands, you can figure out what kind of terminal you’re dealing with, and then manipulate it nearly to your heart’s content. Let’s get started!

About terminfo

The most fundamental question you have to ask is what kind of terminal are you talking to. The answer is in the $TERM environment variable and if you ask your shell to print that variable, you’ll see what it thinks you are using: echo $TERM.
For example, a common type is vt100 or linux console. This is usually set by the system and you shouldn’t change it unless you have a good reason. In theory, of course, you could manually process this information but it would be daunting to have to figure out all the way to do something like clear the screen on the many terminals Linux understands.

That’s why there’s a terminfo database. On my system, there are 43 files in /lib/terminfo (not counting the directories) for terminals with names like dumb, cygwin, ansi, sun, and xterm. Looking at the files isn’t very useful since they are in a binary format, but the infocmp program can reverse the compilation process. Here’s part of the result of running infocmp and asking for the definition of a vt100:


vt100|vt100-am|dec vt100 (w/advanced video),

       am, mc5i, msgr, xenl, xon,

        cols#80, it#8, lines#24, vt#3,

        acsc=``aaffggjjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~,

        bel=^G, blink=E[5m$<2>, bold=E[1m$<2>,

        clear=E[HE[J$<50>, cr=r, csr=E[%i%p1%d;%p2%dr,
 

This might not look much better than the binary version. But you can probably guess that it is telling you, in part, that the bell character (bel) is Control-G (^G). You can also probably guess that E is an escape character and puzzle out how to make characters bold or clear the screen. Some of the data is structural such as 24 lines and 80 columns of output. The capabilities (like xon for using XON/XOFF protocol) are a bit harder to puzzle out without looking it up.

The exact meanings, though, aren’t important. Because we are going to use higher-level constructs to tell tput what we want and it — or at …read more

Source:: Hackaday