13

In zsh, running the command read -p 'erasing all directories (y/n) ?' ans, throws the error,

read: -p: no coprocess

But in bash, it prints a prompt. How do I do this in zsh?

3 Answers3

14

You can still use read, you just need to print a prompt first. In zsh, -p indicates that input should be read from a coprocess instead of indicating the prompt to use.

You can do the following instead, which is POSIX-compliant:

printf >&2 '%s ' 'erase all directories? (y/n)'
read ans

Like for ksh/zsh's read 'var?prompt' or bash's read -p prompt var, the prompt is issued on stderr so as not to pollute the normal output of your script.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
Chris Down
  • 122,090
  • 24
  • 265
  • 262
4

or a more zsh-like way

() {
  local compcontext='yn:yes or no:(y n)'
  vared -cp 'erasing all directories (y/n) ? ' ans
}

Which allows completing the answer.

llua
  • 6,760
  • 24
  • 30
3

Same as in ksh:

IFS= read -r 'ans?erasing all directories (y/n)? '

Also note that zsh's read has the -q for yes/no answers:

if read -q '?erasing all directories (y/n)? '; then
  rm -rf -- *(D/)
fi

It returns true if your enter yes and doesn't require you to press Enter.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
  • 2
    It should be noted that `-q` will not output a trailing newline after the user's reply. You need to do that yourself if you want one. – Kevin May 12 '16 at 20:18
  • Thanks for mentioning `read -q`. Exactly what I need. – Janosh May 25 '20 at 18:57