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

Are you sure? [Y/n]

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

原因是hgpush和hgout听起来很相似,有时当我想要hgoutrepo时,我可能会意外地键入hgpushrepo(两者都是别名)。

更新:如果可以像内置命令一样使用另一个命令,比如:confirm && hg push ssh://…那太好了……只是一个命令,可以询问“是”或“否”,如果是则继续其余的操作。


当前回答

Try,

 #!/bin/bash
 pause ()
 {
 REPLY=Y
 while [ "$REPLY" == "Y" ] || [ "$REPLY" != "y" ]
 do
  echo -e "\t\tPress 'y' to continue\t\t\tPress 'n' to quit"
  read -n1 -s
      case "$REPLY" in
      "n")  exit                      ;;
      "N")  echo "case sensitive!!"   ;; 
      "y")  clear                     ;;
      "Y")  echo "case sensitive!!"   ;;
      * )  echo "$REPLY is Invalid Option"     ;;
 esac
 done
 }
 pause
 echo "Hi"

其他回答

这并不完全是一个“询问是或否”,而只是一个hack: alias hg push…不是hgpushrepo,而是hgpushrepoconfirmedpush,当我能把整个事情说清楚的时候,左脑已经做出了一个合乎逻辑的选择。

这可能有点太短了,但对于我自己的私人使用,它工作得很好

read -n 1 -p "Push master upstream? [Y/n] " reply; 
if [ "$reply" != "" ]; then echo; fi
if [ "$reply" = "${reply#[Nn]}" ]; then
    git push upstream master
fi

read -n 1只读取一个字符。不需要按回车键。如果不是“n”或“n”,则假定是“Y”。按回车键也意味着Y。

(至于真正的问题:使它成为一个bash脚本,并更改您的别名指向该脚本,而不是之前所指向的内容)

这些是哈米什的回答中更紧凑、更通用的形式。它们可以处理任何大小写字母的混合:

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

或者,对于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

注意:如果$response是一个空字符串,它将给出一个错误。要修复,只需添加引号:"$response"。-在包含字符串的变量中总是使用双引号(例如:更喜欢使用“$@”而不是$@)。

或者,Bash 4.x:

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

编辑:

作为对你的编辑的回应,以下是你如何根据我回答的第一个版本创建和使用确认命令(它将与其他两个类似):

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://..

为了避免显式检查'yes'的这些变体,你可以使用bash正则表达式操作符'=~'和一个正则表达式:

read -p "Are you sure you want to continue? <y/N> " prompt
if [[ $prompt =~ [yY](es)* ]]
then
(etc...)

它测试用户输入是否以“y”或“y”开头,后面是0个或多个“es”。

是的,根据Dennis Williamson的回答

#!/bin/bash
confirm() {
    # call with a prompt string or use a default
    read -r -p "${1:-Are you sure?} [Y/n] " response
    case "$response" in
        @([nN])*([oO]))
            false
            ;;
        *)
            true
            ;;
    esac
}