Make text disappear after user input

Is there a way you can make the displayed content disappear just after user gives input ?

For example, take this file below

read -n 1 -p 'how are you ? ' var
if [ "$var" == "y" ]
    echo 'Have fun'
    echo 'Go to Doctor'

If you run this, the output is

how are you ? yHave fun

I am looking for something that let me make how are you ? disappear as soon as user presses a key

And then after disappearing, print Have fun

So, I want the last output of the above program to be only

Have fun

Note: Also, anything above this script that is printed on the shell screen should not be erased.

I am using bash

Asked By: GypsyCosmonaut


Use a carriage return (r). This special character (a leftover from the days of mechanical typewriters) will move the cursor back to the beginning of the line. Then, you need as many spaces as the message you want to delete (this will overwrite the message) and then a second carriage return to go back to the beginning before printing the next message. Something like this:

echo foo
read -n 1 -p 'how are you ? ' var
if [ "$var" == "y" ]
    printf 'r                rHave funn'
    printf 'r                rGo to Doctorn'

Running the script above prints:

Have fun        
Answered By: terdon

You can use:

tput cr

(or printf 'r') to move the cursor to the beginning of the line. Followed by:

tput el

to delete everything up to the end of the line. (tcsh and zsh also have the echotc builtin which you can use with the termcap equivalent of that terminfo el: echotc ce (also echoti el in zsh))

Answered By: Stéphane Chazelas

There are a number of ways to do this, ranging from idiot proof to elegant.

The most foolproof method (although the most work) is backspace space backspace repeated however many times needed. This works on everything but teletypes (removing ink from paper is a challenge).

Next up the scale is carriage return spaces carriage return. This does not work with terminal emulators that insert a linefeed before or after each carriage return (this is an option minicom and others may be configured to have).

Then there is the terminal specific tricks I will mention only termcap capability codes as termcap and terminfo databases can show usage. (Here is a list.)

Simple for a single line is move to column (ch) followed by clear to end of line (ce).

For more complicated cases including multi line responses there is save absolute position (sc), prompt, read response, restore cursor position (rc), clear to end of screen (cd).

In most cases you can hardcode the vt100 values for the last two answers as most terminal emulators are compatible with it. Of course not all terminals support those options, but those that don’t are rare and obsolete.

Answered By: hildred
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.