0

I read multiple answers with varying complexities. Most are working well when the input is typed manually.

For example: https://stackoverflow.com/a/20913871/1841533 .

Here is my sample code, very close to the one in that answer:

_delay_end_input_=2
printf "%s\n" "answer: "
IFS= read -d '' -n 1 theanswer
while IFS= read -d '' -n 1 -t ${_delay_end_input_} more ; do 
  theanswer="${theanswer}${more}"
done

This also works great when I type the answer manually, ie: character by character...

But if I paste a line (or several) : it echoes the "remaining buffer" after each character is read... making a mess of the display.

I haven't yet found a way to hide this, while keeping the normal echoing on screen. (ie, if typing or pasting, I still want to see what is typed/pasted)

Short example: Here is the (good) prompt while I type manually "abcd", character by character:

answer: abcd

But if I supply "abcd" by pasting it in a single moment with the mouse, it messes up the echoing by repeating after each character is read the remaining entire buffer:

answer: abcdbcdcdd

tl/dr: the snippet works great when entering character by character, but echoes remaining reading buffer after reading each char of a pasted entry.

0

I may have found a workaround... But I also hope someone gives out something better.

Corrected code: I hide the normal echo, and I echo it myself after each read:

stty_orig=`stty -g`  ### added this
stty -echo           ### added this
_delay_end_input_=2
printf "%s\n" "answer: "
IFS= read -d '' -n 1 theanswer
printf "$theanswer" >&2 ;  ### added this
while IFS= read -d '' -n 1 -t ${_delay_end_input_} more ; do
  printf "$more" >&2 ;  ### added this
  theanswer="${theanswer}${more}"
done

stty $stty_orig  ### added this

It seems up to now to do everything I needed... But I dislike printing to stderr that way... (maybe best to printf to /dev/tty instead?)

edit: a big drawback is : difficult to also handle "backspaces" or dels: if the person entering 1 or multiple lines of text wants to change something, it's quite hairy to interpret the corrective keys... Having a readline allowing 1 or several lines of input would be the best here... (maybe perl has one?)

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.