Bash 脚本中是否有任何默认函数/实用程序来提示用户选择是/否?

Bash 脚本中是否有任何默认函数/实用程序来提示用户选择是/否?

有时我需要询问用户“是/否”来确认某事。

通常我会使用如下方法:

# Yes/no dialog. The first argument is the message that the user will see.
# If the user enters n/N, send exit 1.
check_yes_no(){
    while true; do
        read -p "$1" yn
        if [ "$yn" = "" ]; then
            yn='Y'
        fi
        case "$yn" in
            [Yy] )
                break;;
            [Nn] )
                echo "Aborting..."
                exit 1;;
            * )
                echo "Please answer y or n for yes or no.";;
        esac
    done;
}

有没有更好的方法?这个实用程序可能已经在我的/bin文件夹中了?

答案1

啊,有一些内置的东西:zenity是一个图形对话程序:

if zenity --question --text="Is this OK?" --ok-label=Yes --cancel-label=No
then
    # user clicked "Yes"
else
    # user clicked "No"
fi

除 之外zenity,您还可以使用以下之一:

if dialog --yesno "Is this OK?" 0 0; then ...
if whiptail --yesno "Is this OK?" 0 0; then ...

答案2

我觉得这很好。我只是想让它少一点“不成功便成仁”的感觉:

  • 如果是“Y”则return 0
  • 如果“N”则return 1

这样你就可以做类似的事情:

if check_yes_no "Do important stuff? [Y/n] "; then
    # do the important stuff
else
    # do something else
fi
# continue with the rest of your script

根据@muru 的select建议,该功能可以非常简洁:

check_yes_no () { 
    echo "$1"
    local ans PS3="> "
    select ans in Yes No; do 
        [[ $ans == Yes ]] && return 0
        [[ $ans == No ]] && return 1
    done
}

答案3

作为结论,我写了这个脚本

#!/bin/bash

usage() { 
    echo "Show yes/no dialog, returns 0 or 1 depending on user answer"
    echo "Usage: $0 [OPTIONS]
    -x      force to use GUI dialog
    -m <string> message that user will see" 1>&2
    exit 1;
}

while getopts m:xh opts; do
    case ${opts} in
        x) FORCE_GUI=true;
            ;;
        m) MSG=${OPTARG}
            ;;
        h) usage
            ;;
    esac
done

if [ -z "$MSG" ];then
    usage
fi

# Yes/no dialog.
# If the user enters n/N, return 1.
while true; do
    if [ -z $FORCE_GUI ]; then
        read -p "$MSG" yn
        case "$yn" in
            [Yy] )
                exit 0;;
            [Nn] )
                echo "Aborting..." >&1
                exit 1;;
            * )
                echo "Please answer y or n for yes or no.";;
        esac
    else
        if [ -z $DISPLAY ]; then echo "DISPLAY variable is not set" >&1 ; exit 1; fi
        if zenity --question --text="$MSG" --ok-label=Yes --cancel-label=No; then
            exit 0
        else
            echo "Aborting..." >&1
            exit 1
        fi
    fi
done;

可以找到最新版本的脚本这里. 填写随意更改/编辑

答案4

我正在使用以下内容:

  • 默认为否:
    read -p "??? Are You sure [y/N]? " -n 1
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "!!! Canceled by user."
        exit 1
    fi
  • 默认为是:
    read -p "??? Are You sure [Y/n]" -n 1
    if [[ $REPLY =~ ^[Nn]$ ]]; then
        echo "!!! Canceled by user."
        exit 1
    fi

相关内容