Wednesday, February 18, 2015

Clearing the Screen vs Clearing the Scroll Buffer in a Linux or Cygwin shell

There are many ways of getting to a command line shell in the Unix/Linux world.  Built-in terminal emulators, ssh, PuTTY, mintty, and many more.  It would be nice if there was a common way to clear the screen so that you could create portable scripts that need this.  For example, if you needed the ability to create a simple text UI session in a shell.  Not only that, but how about a portable way to clear the screen along with the entire scroll buffer as well?

I decided to write this blog entry because there is a lot of confusing information on the topic out on the web.  Here I try to give you the two simplest, most portable ways to solve this problem:

In the examples below, I define two aliases that should be placed in your .kshrc or .bashrc file.

alias cls='tput clear'
alias clb='tput reset'

    cls -- is short for "clear screen"
    clb -- is short for "clear buffer"

The clear screen command simply scrolls the buffer up one page to give you a clear screen.
The clear buffer command erases the entire scroll buffer, including the current screen.

These two commands should work in any linux-like shell environment (including Cygwin's mintty shell) where the 'ncurses' library has been installed.
 
    [ To check if ncurses is installed, run this command:
         "$ which tput"
       If the command is found, you are good to go. ]

As an alternative, you can use the following two alias definitions, which may be used even without the ncurses libraries.

alias cls='echo -e "\x1b[2J"'
alias clb='echo -e "\x1bc"'

These escape sequences are recognized by any terminal emulating the 'xterm' standard.

No comments:

Post a Comment