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
#!/bin/bash read -n 1 -p 'how are you ? ' var if [ "$var" == "y" ] then echo 'Have fun' else echo 'Go to Doctor' fi
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
So, I want the last output of the above program to be only
Note: Also, anything above this script that is printed on the shell screen should not be erased.
I am using
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 funn' else printf 'r rGo to Doctorn' fi
Running the script above prints:
$ foo.sh foo Have fun
You can use:
printf 'r') to move the cursor to the beginning of the line. Followed by:
to delete everything up to the end of the line. (
zsh also have the
echotc builtin which you can use with the
termcap equivalent of that
echotc ce (also
echoti el in
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.