Linux – How do commands like top update output without appending in the console

consolelinuxputtyterminal-emulatorunix

I connect to remote Linux servers using SSH via PuTTY terminal emulator. I notice the commands I run and the output on console keep appending in the terminal window. I mean, when I use scrollbar and scroll up/down, I can see the previous commands I have run and their output, like on a printed paper. However, some commands like top constantly update the output without appearing as appending on the console. How does it work?

Best Answer

There are, potentially, two mechanisms at work here.

One is use of ANSI escape codes (and other non-ANSI codes in some cases), as mentioned by Martin Prikryl in their answer, to implement a text-based pseudographical interface. The bare minimum for this is exactly two specific ANSI escape codes, ^[[2J, which erases everything on the screen, and ^[[;H, which moves the cursor to the top left of the screen. By combining those, you can write out the contents of each ‘frame’ one by one without adding to the scrollback buffer. Most applications actually use a lot more than just those (for example, there are a set of codes for moving the cursor in arbitrary directions, and it’s pretty normal to use these to skip over parts of the screen that should be ‘empty’). In practice, most (but by no means all) larger applications utilize either libcurses (or more often, ncurses) or a direct equivalent to handle all of this for them.

The other possibility, which is usually combined with the use of ANSI escape codes to manipulate the screen contents, is a special feature originally provided by xterm, but now widely implemented by most decent terminal emulators, called the alternate screen buffer. There are a pair of escape codes (^[[?1049h and ^[[1049l) used to switch between this and the regular scrollback buffer. By switching to the alternate screen buffer before presenting a textual UI, programs can completely avoid altering the scrollback buffer at all, which not only prevents you from scrolling without having to intercept the keystrokes that would normally scroll, it also lets the program do things like let you inspect the existing terminal contents from before the program was run (and makes it easier to see what you were doing before you opened that full-screen application).

Related Question