在这种特殊情况下,我想在 Bash 中添加一个确认
Are you sure? [Y/n]
对于Mercurial的hg push ssh://username@www.example.com//somepath/morepath
,其实就是一个别名。是否有一个标准的命令可以添加到别名中来实现它?
原因是 hg push
和 hg out
听起来很相似,有时当我想要 hgoutrepo
时,我可能会不小心输入 hgpushrepo
(都是别名)
更新:如果它可以像内置命令一样带有另一个命令,例如:confirm && hg push ssh://...
那'很棒...只是一个命令,可以请求 yes
或 no
,如果 yes
则继续其余的。
最佳答案
这些是 Hamish's answer 的更紧凑和通用的形式.他们处理大小写字母的任何混合:
read -r -p "Are you sure? [y/N] " response
case "$response" in
[yY][eE][sS]|[yY])
do_something
;;
*)
do_something_else
;;
esac
或者,对于 Bash >= 3.2 版:
read -r -p "Are you sure? [y/N] " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]
then
do_something
else
do_something_else
fi
注意:如果$response
为空串,会报错。要修复,只需添加引号:"$response"
。 – 始终在包含字符串的变量中使用双引号(例如:更喜欢使用 "$@"
而不是 $@
)。
或者,Bash 4.x:
read -r -p "Are you sure? [y/N] " response
response=${response,,} # tolower
if [[ "$response" =~ ^(yes|y)$ ]]
...
编辑:
作为对您编辑的回应,以下是您如何根据我回答中的第一个版本创建和使用 confirm
命令(它与其他两个版本的工作方式类似):
confirm() {
# call with a prompt string or use a default
read -r -p "${1:-Are you sure? [y/N]} " response
case "$response" in
[yY][eE][sS]|[yY])
true
;;
*)
false
;;
esac
}
要使用此功能:
confirm && hg push ssh://..
或
confirm "Would you really like to do a push?" && hg push ssh://..
关于bash - 在 Bash 中,如何将 "Are you sure [Y/n]"添加到任何命令或别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3231804/