22

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.

2
  • Cannot confirm on a fresh zsh 4.3.10 install; % read a works fine here. May 22, 2012 at 22:04
  • This is using iterm on OS X; read does work on Linux machines. May 22, 2012 at 22:37

1 Answer 1

36

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
2
  • 3
    vared -p 'What would you like to do?: ' -c tmp
    – zzapper
    Nov 16, 2014 at 23:43
  • 2
    So cool! Didn't know about the vared builtin. Turns out, zshzle man page is definitely worth at least skimming through.
    – ratijas
    Nov 22, 2018 at 21:57

You must log in to answer this question.

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