[使用zsh,我试图在~/.zprofile
中迈出一步,以交互方式询问是/否样式问题。起初我尝试了this bash-style approach,但是我看到了这种形式的错误:
read: -p: no coprocess
((我知道zsh语法通常与bash的语法不同-我曾尝试在其前面加上sh仿真命令-emulate -LR sh
-但没有区别)。
此页面暗示语法可能有所不同,因此在this page和zsh手册页的指导下,我改用了此方法:
read -q REPLY?"This is the question I want to ask?"
这将失败,并出现以下形式的错误:
/home/user/.zprofile:5: no matches found: REPLY?"This is the question I want to ask?"
我如何用zsh问一个简单的是/否问题?理想情况下,该命令只需吞下一个字符,无需按Enter / Return键即可,并且是“安全的”-即,除非输入“ Y”或“ y”,否则后续测试默认为no / false。
如果第一个参数包含'?',则该单词的其余部分将在外壳是交互式时用作标准错误的提示。
您必须引用整个参数
read -q "REPLY?This is the question I want to ask?"
这将提示您输入This is the question I want to ask?
并返回在REPLY
中按下的字符。
如果不引号,zsh
尝试将参数作为文件名进行匹配。如果找不到任何匹配的文件名,则会显示no matches found
。
请参阅ZSH Manual了解ZSH的阅读文档。试试:
read REPLY\?"This is the question I want to ask?"
我要添加此答案,因为每次您想请求用户确认时,您也都希望对其采取行动。这是一个函数,提示您输入read -q
(谢谢,还有其他答案!),然后根据结果进行分支以完成您想要的操作(在本例中为git的东西):
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
set -x
git add . && git commit -m 'haha git goes brrr' && git pull
{ set +x; } 2>/dev/null
else
echo
echo "'$choice' not 'Y' or 'y'. Exiting..."
fi
}