Unix & Linux
bash read
Updated Sun, 17 Jul 2022 14:37:12 GMT

(How) can I get `read var` to add the literal \b (backspace) to var?


For example, the user types foofoo\b\b\bbar, presses enter and gets a var equaling foofoo\b\b\bbar instead of foobar. Yes, the user loses the deletion feature so they need to use another shortcut for deletion. Or at least the other way around: normal backspace (pressing) gives them foobar and some modifier + backspace-key gives them literal backspaces.

Is there a way to enable read to accept literal backspaces?




Solution

This script (in bash) will accept any character except

  1. ^C (ASCII 03 ETX )
  2. ^J (ASCII 0A LF )
  3. ^M (ASCII 0D CR )
  4. ^Z (ASCII 1A SUB )
  5. ^\ (ASCII 1C FS )

including all other control characters:

#!/bin/bash
while IFS= read -srn1 a ;do
    [[ "${a+x$a}" = "x" ]] && break
    var=$var$(printf '%s' "$a")
    printf '%s' "$a"
done
printf '\n%s\n' "$var"

Type the backspaces as CTRL-H.

Replace:

printf '\n%s\n' "$var"

with:

printf '%s' "$var" | od -An -tx1

To actually "see" the byte values.





Comments (2)

  • +0 – Simply beautiful. — Jan 28, 2018 at 17:19  
  • +1 – And most of those are because the terminal intercepts them, you could change the terminal settings to not interrupt on ^C, for example. But you'll have to decide if that's a good idea. — Jan 28, 2018 at 17:22