这些是更紧凑和通用的形式Hamish's answer https://stackoverflow.com/questions/3231804/in-bash-how-to-add-are-you-sure-y-n-to-any-command-or-alias/3231821#3231821。它们处理大小写字母的任意混合:
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)$ ]]
...
Edit:
为了响应您的编辑,您可以按照以下方式创建和使用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://..
or
confirm "Would you really like to do a push?" && hg push ssh://..