Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prompt for yes/no style confirmation in a zsh script?

Tags:

Using zsh, I'm trying to put a step in my ~/.zprofile where I interactively ask a yes/no style question. At first I tried this bash-style approach, but I saw errors of this form:

read: -p: no coprocess

(I'm aware that typically the zsh syntax is different from bash's - I tried preceding it with a sh emulation command - emulate -LR sh - but it made no difference).

This page implied the syntax might be different, so guided by this page and the zsh man page, I tried this instead:

read -q REPLY?"This is the question I want to ask?"

This instead fails with an error of the form:

/home/user/.zprofile:5: no matches found: REPLY?"This is the question I want to ask?"

How can I ask a simple yes/no question with zsh? Ideally the command would just swallow one character, with no need to press Enter/Return, and be 'safe' - i.e. the subsequent test defaults to no/false unless 'Y' or 'y' are entered.

like image 594
Andrew Ferrier Avatar asked Mar 02 '13 11:03

Andrew Ferrier


People also ask

How do you ask yes or no in bash?

In that case, we can simply wrap our yes/no prompt in a while loop. #!/bin/bash while true; do read -p "Do you want to proceed? (yes/no) " yn case $yn in yes ) echo ok, we will proceed; break;; no ) echo exiting...; exit;; * ) echo invalid response;; esac done echo doing stuff...

How do you prompt a shell script?

You can use the built-in read command ; Use the -p option to prompt the user with a question. It should be noted that FILEPATH is the variable name you have chosen, and is set with the answer to the command prompt.

How do you say yes to all in CMD?

-y, --yes, --assume-yes Automatic yes to prompts; assume "yes" as answer to all prompts and run non-interactively.


1 Answers

From zsh - read

If the first argument contains a ‘?’, the remainder of this word is used as a prompt on standard error when the shell is interactive.

You must quote the entire argument

read -q "REPLY?This is the question I want to ask?" 

this will prompt you with This is the question I want to ask? and return the character pressed in REPLY.

If you don't quote the question mark, zsh tries to match the argument as a filename. And if it doesn't find any matching filename, it complains with no matches found.

like image 124
Olaf Dietsche Avatar answered Oct 21 '22 02:10

Olaf Dietsche