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


当前回答

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

其他回答

这是我在其他地方找到的,有更好的版本吗?

read -p "Are you sure you wish to continue?"
if [ "$REPLY" != "yes" ]; then
   exit
fi

尝试read shell内置:

read -p "Continue (y/n)?" CONT
if [ "$CONT" = "y" ]; then
  echo "yaaa";
else
  echo "booo";
fi
#!/bin/bash
echo Please, enter your name
read NAME
echo "Hi $NAME!"
if [ "x$NAME" = "xyes" ] ; then
 # do something
fi

我是一个在bash中读取并回显结果的简短脚本。

这样您就可以得到“y”、“yes”或“Enter”

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

如果您正在使用zsh,请尝试以下操作:

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

下面是我使用的函数:

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

输出始终为“是”或“否”默认为“否”除“y”或“yes”之外的所有内容都返回“no”,因此对于危险的bash脚本来说是非常安全的它不区分大小写,“Y”、“是”或“是”与“是”相同。

我希望你喜欢,干杯