How can I prompt for yes/no style confirmation in a zsh script?
I'm adding this answer because every time you want to ask the user for confirmation, you also want to act on it. here's a function that prompts with read -q
(thanks, other answers!) and branches on the result to do what you want (in this case, git stuff):
git_commit_and_pull() {
# http://zsh.sourceforge.net/Doc/Release/Shell-Builtin-Commands.html#index-read
if read -q "choice?Press Y/y to continue with commit and pull: "; then
git add . && git commit -m 'haha git goes brrr' && git pull
else
echo
echo "'$choice' not 'Y' or 'y'. Exiting..."
fi
}
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
.