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

Are you sure? [Y/n]

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

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

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


当前回答

不一样,但不管怎样都行得通。

#!/bin/bash  
i='y'  
while [ ${i:0:1} != n ]  
do  
    # Command(s)  
    read -p " Again? Y/n " i  
    [[ ${#i} -eq 0 ]] && i='y'  
done  

输出: 一遍吗?Y / n n 一遍吗?Y / n任何 一遍吗?Y / n 7 一遍吗?Y / n & 一遍吗?Y / n nsijf $

现在只检查$i读取的第一个字符。

其他回答

read -r -p "Are you sure? [Y/n]" response
  response=${response,,} # tolower
  if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
      your-action-here
  fi

这是我的解决方案,使用本地化正则表达式。所以在德语中,“Ja”的“j”也会被解释为“是”。

第一个参数是问题,如果第二个参数是y,那么yes将是默认答案,否则no将是默认答案。如果答案是“是”,则返回值为0,如果答案是“否”,则返回值为1。

function shure(){
    if [ $# -gt 1 ] && [[ "$2" =~ ^[yY]*$ ]] ; then
        arg="[Y/n]"
        reg=$(locale noexpr)
        default=(0 1)
    else
        arg="[y/N]"
        reg=$(locale yesexpr)
        default=(1 0)
    fi
    read -p "$1 ${arg}? : " answer
    [[ "$answer" =~ $reg ]] && return ${default[1]} || return ${default[0]}
}

下面是一个基本用法

# basic example default is no
shure "question message" && echo "answer yes" || echo "answer no"
# print "question message [y/N]? : "

# basic example default set to yes
shure "question message" y && echo "answer yes" || echo "answer no"
# print "question message [Y/n]? : "

以下是您需要的大致片段。 让我看看如何转发这些论点。

read -p "Are you sure you want to continue? <y/N> " prompt
if [[ $prompt == "y" || $prompt == "Y" || $prompt == "yes" || $prompt == "Yes" ]]
then
  # http://stackoverflow.com/questions/1537673/how-do-i-forward-parameters-to-other-command-in-bash-script
else
  exit 0
fi

注意这里的yes |命令名:)

这个版本允许你有不止一种情况y或y n或n

Optionally: Repeat the question until an approve question is provided Optionally: Ignore any other answer Optionally: Exit the terminal if you want confirm() { echo -n "Continue? y or n? " read REPLY case $REPLY in [Yy]) echo 'yup y' ;; # you can change what you do here for instance [Nn]) break ;; # exit case statement gracefully # Here are a few optional options to choose between # Any other answer: # 1. Repeat the question *) confirm ;; # 2. ignore # *) ;; # 3. Exit terminal # *) exit ;; esac # REPLY='' }

还要注意:在这个函数的最后一行清除REPLY变量。否则,如果你回显$REPLY,你会看到它仍然设置,直到你打开或关闭你的终端或再次设置它。

不一样,但不管怎样都行得通。

#!/bin/bash  
i='y'  
while [ ${i:0:1} != n ]  
do  
    # Command(s)  
    read -p " Again? Y/n " i  
    [[ ${#i} -eq 0 ]] && i='y'  
done  

输出: 一遍吗?Y / n n 一遍吗?Y / n任何 一遍吗?Y / n 7 一遍吗?Y / n & 一遍吗?Y / n nsijf $

现在只检查$i读取的第一个字符。