Backspace doesn't work inside running bash script

I'm running very simple script which reads line by line and prints entered line back to terminal:

while read CMD; do
    echo $CMD
done

It works fine, but when I'm trying to edit line with backspace character it prints ^?instead of deleting character. And when I press Ctrl + backspace the output is ^H. How could this behavior be fixed so backspace removes character instead of adding these characters? I tried stty erase '^?' command but not successfully.


The problem is that there are many ways to represent a backspace, but the read command doesn't understand all of them. You should be able to configure what exactly is sent when pressing the ← Backspace key in your terminal emulator's settings.

Assuming you're using gnome-terminal as emulator, open the Edit manu and click on Profile preferences. Switch to the Compatibility tab and you should get these options:

gnome-terminal → profile preferences → compatibility

Now you can change the Backspace key generates: setting. You have these five options below available to chose from. I added in braces how they behave on my system:

  • Automatic (works)
  • Control-H (prints ^H instead)
  • ASCII DEL (default, works)
  • Escape sequence (prints ^[[3~ instead)
  • TTY Erase (works)

I had the same problem, using bash in Gnome-Terminal.

Note that on the command line, the backspace works as expected, but when my program (a simple TCP socket based chat client) is reading from stdin, the backspace character prints (echoes back to the screen) ^?instead of deleting the last character.

Use # stty icanon to allow the "canonical (cooked) mode". See some explanation here https://unix.stackexchange.com/questions/131105/how-to-read-over-4k-input-without-new-lines-on-a-terminal

Some more background to my problem/solution: I had a problem where I need to paste more than 4k characters. And during that research, I was led to the above link. I used # stty -icanon to disable the 4k limit, but lost the ability to use backspace (erase).