在这种特殊情况下,我想在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"

其他回答

在游戏后期,我创建了前面答案的确认函数的另一个变体:

confirm ()
{
    read -r -p "$(echo $@) ? [y/N] " YESNO

    if [ "$YESNO" != "y" ]; then
        echo >&2 "Aborting"
        exit 1
    fi

    CMD="$1"
    shift

    while [ -n "$1" ]; do
        echo -en "$1\0"
        shift
    done | xargs -0 "$CMD" || exit $?
}

使用它:

confirm your_command

特点:

打印您的命令作为提示符的一部分 使用NULL分隔符传递参数 保留命令的退出状态

错误:

Echo -en与bash一起工作,但在shell中可能会失败 如果参数干扰echo或xargs,则可能失败 因为编写shell脚本很难,所以有无数的其他bug

在/etc/bashrc文件中添加以下内容。 这个脚本添加了一个常驻的“函数”,而不是名为“confirm”的别名。


function confirm( )
{
#alert the user what they are about to do.
echo "About to $@....";
#confirm with the user
read -r -p "Are you sure? [Y/n]" response
case "$response" in
    [yY][eE][sS]|[yY]) 
              #if yes, then execute the passed parameters
               "$@"
               ;;
    *)
              #Otherwise exit...
              echo "ciao..."
              exit
              ;;
esac
}

是的,根据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
}

我知道这是一个老问题,但这可能会帮助到一些人,它还没有在这里解决。

有人问我如何在接收文件输入的脚本中使用rm -i。由于脚本的文件输入通常是从STDIN接收的,因此我们需要更改它,以便从STDIN接收对rm命令的响应。下面是解决方案:

#!/bin/bash
while read -u 3 line
do
 echo -n "Remove file $line?"
 read -u 1 -n 1 key
 [[ $key = "y" ]] &&  rm "$line"
 echo
done 3<filelist

如果按下“y”键以外的任何键(仅限小写),文件将不会被删除。没有必要在键后按回车键(因此echo命令发送新行到显示器)。 请注意,POSIX bash“read”命令不支持-u开关,因此需要寻找解决方案。

如果用户不确定,我喜欢尽快退出,并且我喜欢代码可读性强且简短。这取决于你是否希望用户在回答后按下回车键,

按回车键,

read -p "Warning: something scary: Continue (Y/N)? " reply
[ $reply != 'Y' ] && [ $reply != 'y' ] && echo 'Aborting' && exit 1
echo 'Scary thing'

或者如果你不想等用户按回车键,

read -n1 -p "Warning: something scary: Continue (Y/N)? " reply
echo ''
[ $reply != 'Y' ] && [ $reply != 'y' ] && echo 'Aborting' && exit 1
echo 'Scary thing'

其他答案的背景是-n1标志和其他读选项。第二个变体中的echo "是为了让后续输出出现在新行上,因为用户不必按Return,所以没有换行符被返回到终端。