首页 文章

如何在bash脚本中提示用户进行确认? [重复]

提问于
浏览
471

这个问题在这里已有答案:

我想快点说“你确定吗?”提示在潜在危险的bash脚本顶部进行确认,最简单/最好的方法是什么?

10 回答

  • 4

    用例/ esac .

    read -p "Continue (y/n)?" choice
    case "$choice" in 
      y|Y ) echo "yes";;
      n|N ) echo "no";;
      * ) echo "invalid";;
    esac
    

    优点:

    • 整洁

    • 可以更轻松地使用"OR"条件

    • 可以使用字符范围,例如[yY] [eE] [sS]接受单词"yes",其中任何字符可以是小写字母或大写字母 .

  • 2
    #!/bin/bash
    echo Please, enter your name
    read NAME
    echo "Hi $NAME!"
    if [ "x$NAME" = "xyes" ] ; then
     # do something
    fi
    

    我是一个简短的脚本,用于读取bash并回显结果 .

  • 27

    这是我使用的功能:

    function ask_yes_or_no() {
        read -p "$1 ([y]es or [N]o): "
        case $(echo $REPLY | tr '[A-Z]' '[a-z]') in
            y|yes) echo "yes" ;;
            *)     echo "no" ;;
        esac
    }
    

    并使用它的一个例子:

    if [[ "no" == $(ask_yes_or_no "Are you sure?") || \
          "no" == $(ask_yes_or_no "Are you *really* sure?") ]]
    then
        echo "Skipped."
        exit 0
    fi
    
    # Do something really dangerous...
    
    • 输出始终为"yes"或"no"

    • 默认为"no"

    • 除"y"或"yes"之外的所有内容都返回"no",因此对于危险的bash脚本来说非常安全

    • 并且它不区分大小写,"Y","Yes"或"YES"作为"yes"工作 .

    我希望你喜欢它,
    干杯!

  • 758

    这是我在别处找到的,是否有更好的版本?

    read -p "Are you sure you wish to continue?"
    if [ "$REPLY" != "yes" ]; then
       exit
    fi
    
  • 18
    read -p "Are you sure? " -n 1 -r
    echo    # (optional) move to a new line
    if [[ $REPLY =~ ^[Yy]$ ]]
    then
        # do dangerous stuff
    fi
    

    Edit

    我收录了 levislevis85 的建议(谢谢!)并将 -n 选项添加到 read 以接受一个字符而无需按Enter键 . 您可以使用其中一个或两个 .

    此外,否定的形式可能如下所示:

    read -p "Are you sure? " -n 1 -r
    echo    # (optional) move to a new line
    if [[ ! $REPLY =~ ^[Yy]$ ]]
    then
        [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 # handle exits from shell or function but don't exit interactive shell
    fi
    

    但是,正如Erich所指出的,在某些情况下,例如由于脚本在错误的shell中运行而导致的语法错误,否定的表单可能允许脚本继续执行"dangerous stuff" . 失败模式应该有利于最安全的结果,因此只应使用第一个未被否定的 if .

  • 5

    试试 read shell内置:

    read -p "Continue (y/n)?" CONT
    if [ "$CONT" = "y" ]; then
      echo "yaaa";
    else
      echo "booo";
    fi
    
  • 14

    qnd:用

    read VARNAME
    echo $VARNAME
    

    没有readline支持的单行响应 . 然后根据需要测试$ VARNAME .

  • 128

    通过这种方式,您可以得到“是”或“输入”

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

    如果你使用zsh试试这个:

    read "response?Are you sure ? [Y/n] "
    response=${response:l} #tolower
    if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
        your-action-here
    fi
    
  • 27
    [[ -f ./${sname} ]] && read -p "File exists. Are you sure? " -n 1
    
    [[ ! $REPLY =~ ^[Yy]$ ]] && exit 1
    

    在函数中使用它来查找现有文件并在覆盖之前提示 .

  • 2
    echo are you sure?
    read x
    if [ "$x" = "yes" ]
    then
      # do the dangerous stuff
    fi
    

相关问题