First of all your question has nothing to do with bash but with the terminal. The terminal is responding for displaying the text of the programs and bash itself has no control over the programs once they launched.
Terminals offer control sequences to control color, font, cursor position
and more. For a list of standardized terminal sequences have a look at
http://www.termsys.demon.co.uk/vtansi.htm You can for example
- position the cursor at the beginning of the line
- delete the line afterwards
- write a new line
to create a progress bar.
More advanced terminal escape sequences are typically terminal
dependent, e.g. work only with Eterm or xterm. ncurses -
is a programming library which to
create interactive programs with the terminal so you won't have to use escape sequences.
How to overwrite an existing line with terminal sequences
echo long text
printf "\033[1A" # move cursor one line up
printf "\033[K" # delete till end of line
How to overwrite an existing line without terminal sequence
One simple solution is to not write a newline at the end but write carriage return, which basically resets the cursor to the beginning of the line, e.g:
echo -n first
echo -ne "\rsecond"
\r or carriage return will put the cursor at the beginning of the line and allows you to overwrite the content of the line.
Switch between buffers like
The behavior of
less is also due to a more advanced terminal feature, the
In VT102 mode, there are escape sequences to activate and deactivate an alternate screen
buffer, which is the same size as the display area of the window. When activated, the
current screen is saved and replaced with the alternate screen. Saving of lines scrolled
off the top of the window is disabled until the normal screen is restored. The term‐
cap(5) entry for xterm allows the visual editor vi(1) to switch to the alternate screen
for editing and to restore the screen on exit. A popup menu entry makes it simple to
switch between the normal and alternate screens for cut and paste.
http://rosettacode.org/wiki/Terminal_control/Preserve_screen lists some example how to do it yourself, either via tput or via some escape sequences.