Bash – How does “man” restore the screen when I quit the program

bashmanshellterminal

If I open a man page of a program like cat or ls, it prints (may not be the appropriate word) the contents of the man page and when I press q, it shows the screen just like before invoking the man command. How does the restore happen? What erases everything and then prints the previous contents of the shell?

Example:

[VAR121@Tesla Testing]$  man ls

Output:

LS(1)                                                        User Commands                                                        LS(1)

NAME
       ls - list directory contents

SYNOPSIS
       ls [OPTION]... [FILE]...

 ............

When I press q, the screen goes back to shells default appearance, such as the prompt shown below.

[VAR121@Tesla Testing]$  man ls
[VAR121@Tesla Testing]$

How is the screen restored ?

Best Answer

"Clearing" and "restoring" the screen is actually a function of the terminal emulator you are using (xterm, gnome-terminal, konsole, screen).

By default, the pager that man uses is less.

From man 1 man

   -P  pager
          Specify  which pager to use.  This option overrides the 
          MANPAGER environment variable, which in turn overrides 
          the PAGER variable.  By default, man  uses /usr/bin/less -is.

When less is invoked, an altscreen is launched by the terminal emulator to display the contents of the man page. When less exits, the altscreen is destroyed and the terminal displays what was saved in the buffer.

There is an answer here which discusses this further and how to keep programs like less from launching an altscreen and thus clearing the screen when it exits. In a nutshell, you could define an environment variable so that less does not launch an altscreen on invocation. If you are using bash, place this in ~/.bashrc:

export MANPAGER="/usr/bin/less -r -X -is"