At a low level, you send a terminal program a set of control characters that tell it what to do. This may be too difficult to manage manually.
So instead, you can look at a console library such as ncurses , which can handle all this complexity for you.
Regarding specifically to the previous content that appears after the program is released, this is actually the xterm function that vim uses and which most modern terminals support. It is called an "alternate screen" or simply an "alt screen." Essentially, you are talking about the terminal program, “Okay, now switch to a completely new screen, we will return to another later.”
The command to switch to the alternate screen is usually \E[?47h , and the command to \E[?47h back \E[?47l For fun, try the following:
echo -e "\033[?47h"
and then to return:
echo -e "\033[?47l"
Or for a more complete solution that relies less on your shell to install everything correctly (these sequences are commonly used by vim):
echo -e "\0337\033[?47h" # Save cursor position & switch to alternate screen # do whatever #Clear alternate screen, switch back to primary, restore cursor echo -e "\033[2J\033[?47l\0338"
source share