1

I use printf "input: "; read -e. I type something then I press Backspace. When reaching the last character, this deletes the input: part together with it. Backspace doesn't misbehave if I hadn't typed anything before or if I used simple read (no Readline).

  • 1
    I can't reproduce this with bash 4.4 on OpenBSD. If you're using bash you could also try read -p 'input: ' -e. – Kusalananda Feb 1 '18 at 9:48
  • @Kusalananda I reproduced with bash 4.3.38 on Ubuntu 16.04.3 LTS. – Weijun Zhou Feb 1 '18 at 9:56
  • Could you please confirm what shell you are using? The read in zsh also has an -e option but with different semantics from bash. – Kusalananda Feb 1 '18 at 10:00
  • I can reproduce it with bash 4.4.12, not with zsh. – pfnuesel Feb 1 '18 at 10:04
1

A read -e calls the readline library. Which gives access to several editing tools that a plain read does not have. However, it assumes an "empty line".

A workaround to this problem is to give something (like an space) to avoid the "empty line" assumption:

printf 'input:'; read -e -p ' '

But since that is using the -p option already, it might be simpler to write:

read -e -p 'input: '
  • This is the more direct solution to my problem. – glarry Jan 19 at 23:39
5

read in bash is a builtin command. read -e uses the bash full-screen editing via the readline library (i.e. it understands how to go back to the previous line, move the cursor left and right through the inputted text, etc.). It may use cursor addressing codes to optimize the output to the screen.

However it expects that the cursor is at the beginning of the line when it begins, and sometimes it's faster to clear the whole line when removing the input than to remove the individual characters. This is what is messing up your prompt, which moves the cursor to the right without bash knowing about it.

The same thing can happen when using terminal escapes in your prompt (e.g. to set a colour, or to set the terminal title). For this purpose bash has special escapes to indicate which bytes don't move the cursor.

You should use read -p 'input: ' -e, the -p option for prompting is specially made for this.

  • readline isn't full-screen (it only handles a special case of single-line editing). – Thomas Dickey Dec 8 '18 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.