Better way to read a line of user input in zsh? (e.g. with zle?)

Zsh's read for some reason is echo'ing ^M's instead of accepting them as <Enter> keystrokes. (If -d is set, then they are recognized as <Enter>'s, but still echoed.) It also doesn't support basics like the backspace key.

I can get around this by hacking / running bash,

> a=$(bash -c 'read -e -p "What would you like to do?: " tmp; echo $tmp')
What would you like to do?: eat cake
> echo $a                                                                
eat cake

but I'm wondering if there's a cleaner way.


To input a line of text comfortably under zsh, use vared. Using vared instead of read invokes zle, which is the equivalent of passing -e in bash to invoke readline.

vared -p 'What would you like to do?: ' -c tmp

The behavior you describe with plain read looks like a misconfigured terminal rather than a shell issue. Run stty -a to show your terminal settings, and make sure that eol is set to ^M and erase is set to what your Backspace key sends. Depending on the operating system and how it's set up and on the terminal, Backspace sends either ^H or ^?. The backspace setting usually goes wrong because of some configuration file that tries to set it manually, so the first thing you should do is track and remove any such misconfiguration. If you find none, review your terminal emulator's settings to check that it isn't set into some historical compatibility mode. If all else fails, add something like this to your ~/.zshrc:

if [[ $(ps -o comm= $PPID) = iterm ]]; then
  stty erase '^?'
fi