bash - 在 Bash 中,如何将 "Are you sure [Y/n]"添加到任何命令或别名?

标签 bash alias confirmation

在这种特殊情况下,我想在 Bash 中添加一个确认

Are you sure? [Y/n]

对于Mercurial的hg push ssh://username@www.example.com//somepath/morepath,其实就是一个别名。是否有一个标准的命令可以添加到别名中来实现它?

原因是 hg pushhg out 听起来很相似,有时当我想要 hgoutrepo 时,我可能会不小心输入 hgpushrepo(都是别名)

更新:如果它可以像内置命令一样带有另一个命令,例如:confirm && hg push ssh://... 那'很棒...只是一个命令,可以请求 yesno,如果 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/

相关文章:

mysql - 为什么从 mysql 获取输出时这个 bash 变量为空?

javascript - ElectronJS npm start/bash : electron-forge: command not found

javascript - 确认 Material 表中的自定义操作 [React]

jquery - SimpleModal 确认并继续原始 href

ruby-on-rails - 从 Rails Controller 删除确认

regex - 将 bash 数组元素传递给循环内的 awk 正则表达式

bash - 询问 MongoDB 是否是 bash 脚本中的 Master

bash - 带参数的命令的 "Aliasing"

google-app-engine - Google Apps 域上的 Google App Engine

iis - 在IIS中设置网站别名以隐藏端口号