read command in zsh throws error

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 '%s ' 'erase all directories? (y/n)'
read ans

Method 2

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.

Method 3

Same as in ksh:

read '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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x