13

How do I handle the backspaces entered, it shows ^? if tried & how read counts the characters, as in 12^?3 already 5 characters were complete(though all of them were not actual input), but after 12^?3^? it returned the prompt, weird. Please help!

-bash-3.2$ read -n 5
12^?3^?-bash-3.2$

3 Answers 3

14

When you read a whole line with plain read (or read -r or other options that don't affect this behavior), the kernel-provided line editor recognizes the Backspace key to erase one character, as well as a very few other commands (including Return to finish the input line and send it). The shortcut keys can be configured with the stty utility. The terminal is said to be in cooked mode when its line editor is active. In raw mode, each character typed on the keyboard is transmitted to the application immediately. In cooked mode, the characters are stored in a buffer and only complete lines are transmitted to the application.

In order to stop reading after a fixed number of characters so as to implement read -n, bash has to switch to raw mode. In raw mode, the terminal doesn't do any processing of the Backspace key (by the time you press Backspace, the preceding character has already been sent to bash), and bash doesn't do any processing either (presumably because this gives the greater flexibility of allowing the script to do its own processing).

You can pass the option -e to enable bash's own line editor (readline, which is a proper line editor, not like the kernel's extremely crude one). Since bash is doing the line edition, it can stop reading once it has the requested number of characters.

0
13

Use read -e:

$ read -e -n 5
13acX

read -e means that:

Readline (see Command Line Editing) is used to obtain the line.

When you do that, you can edit the input in any of the ways you would when writing at the regular shell prompt, including backspace, Home, and so on.

1

read is a bash builtin. (see type read.) You can find documentation with man bash:

   read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
   [...]
          -e     If the standard input is coming from a terminal, readline (see READLINE above) is used to obtain the line.
                 Readline uses the current (or default, if line editing was not previously active) editing settings.

or you can use help read:

read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
      -e                use Readline to obtain the line in an interactive shell

The -e switch enables readline support which basically allows all features available at the shell prompt, including backspace handling.

Therefore read -en 5 should do what you want.

1
  • -e solves the problem but how read reads the 'number of characters entered' is still unanswered. Aug 20, 2014 at 7:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .