在bash,如何添加"确定[Y / N] QUOT;对任何命令或别名? [英] In Bash, how to add "Are you sure [Y/n]" to any command or alias?

查看:281
本文介绍了在bash,如何添加"确定[Y / N] QUOT;对任何命令或别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In this particular case, I'd like to add a confirm in Bash for


Are you sure? [Y/n]

有关Mercurial的汞推SSH://username@www.example.com//somepath/morepath ,这实际上是一个别名。有没有可以添加到别名实现呢?一个标准的命令

for Mercurial's hg push ssh://username@www.example.com//somepath/morepath, which is actually an alias. Is there a standard command that can be added to the alias to achieve it?

原因是,汞推汞柱出可听起来很相似,有时当我想要 hgoutrepo ,我可能accidentlly键入 hgpushrepo (都是别名)。

The reason is that hg push and hg out can sound similar and sometimes when I want hgoutrepo, I may accidentlly type hgpushrepo (both are aliases).

更新:如果它可以像一个内置的与另一个命令的命令,如:确认&安培;汞推SSH:// ... 那简直太好了......只是一个命令,可以要求没有,如果继续与其他

Update: if it can be something like a built-in command with another command, such as: confirm & hg push ssh://... that'd be great... just a command that can ask for a yes or no and continue with the rest if yes.

推荐答案

这是<更加紧凑和灵活的形式href=\"http://stackoverflow.com/questions/3231804/in-bash-how-to-add-are-you-sure-y-n-to-any-command-or-alias/3231821#3231821\">Hamish's回答。他们处理的大写和小写字母的任意混合物:

These are more compact and versatile forms of Hamish's answer. They handle any mixture of upper and lower case letters:

read -r -p "Are you sure? [y/N] " response
case $response in
    [yY][eE][sS]|[yY]) 
        do_something
        ;;
    *)
        do_something_else
        ;;
esac

或者,猛砸> = 3.2版本:

Or, for Bash >= version 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

或者,猛砸4.x的:

read -r -p "Are you sure? [y/N] " response
response=${response,,}    # tolower
if [[ $response =~ ^(yes|y)$ ]]
...

编辑:

在回答您的编辑,这里是你如何创建和使用确认根据我的回答的第一个版本命令(将与其他两个类似的工作):

In response to your edit, here's how you'd create and use a confirm command based on the first version in my answer (it would work similarly with the other two):

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,如何添加&QUOT;确定[Y / N] QUOT;对任何命令或别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆