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

Are you sure? [Y/n]

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

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

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


当前回答

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

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

其他回答

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

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
}

下面的代码结合了两个东西

shop -s nocasmatch将照顾大小写不敏感 if条件会接受两个输入要么你传递yes yes y。 shop -s nocasematch 如果[[sed-4.2.2.]$LINE =~ (yes|y)$]] 然后退出0 fi

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

这个版本允许你有不止一种情况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,你会看到它仍然设置,直到你打开或关闭你的终端或再次设置它。