The intent is to put the cursor at some position on the screen (around the center of the screen), enter some initial text, and prompt the user to enter more text to be saved in a variable, while leaving him the normal readline
line editing capabilities.
My initial attemp was to:
echo
/printf
ing some whitespace,echo
/printf
,read -i "editable pre-text" -e answer
.However I noticed the behavior described below, and crafted the following exemplifying two lines-code to demonstrate it.
When executing the following script
echo -n "______________"
read -e risp
as long as no input is typed, Backspace is ineffective (and this is kind of the behavior I like, as the characters entered by echo
before read
cannot be deleted during read
).
However, typing something (e.g. some text) and then deleting it (completely, up to and including the first typed character) with Backspace, will result in the cursor to jump to the first colon of the terminal as soon as Backspace deletes the first typed character.
In other words, as the script starts, Backspace does nothing, while XBackspace will result in the cursort to jump to the first column of the terminal.
What is the reason for this behvaior, and how can I avoid it?
Given the title of this question I would expect it to be related to the present one, but I can't understand if it really is.
As mentioned in a comment, you should use read
's -p
option to print the prompt, rather than trying to set it up before the read
command.
The -e
option asks read
to use the readline
library to handle the input, allowing a wider range of line-editing characters. However, in order to implement these behaviours, readline
needs to be able to redraw the current line, and that's not possible if there is anything on the current line when the read starts. It's not possible because Unix provides no mechanism for an application to look at what's being displayed on the console. So under some circumstances, readline
will simply clear the line. Using the -p
option allows readline
to output the prompt, and it can then know what the line currently looks like.