Make text disappear after user input
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:
#!/bin/bash
echo foo
read -n 1 -p 'how are you ? ' var
if [ "$var" == "y" ]
then
printf '\r \rHave fun\n'
else
printf '\r \rGo to Doctor\n'
fi
Running the script above prints:
$ foo.sh
foo
Have fun
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
))
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.