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

c0r*_*0rp 14 command-line 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;
}
Run Code Online (Sandbox Code Playgroud)

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

gle*_*man 13

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

if zenity --question --text="Is this OK?" --ok-label=Yes --cancel-label=No
then
    # user clicked "Yes"
else
    # user clicked "No"
fi
Run Code Online (Sandbox Code Playgroud)

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

if dialog --yesno "Is this OK?" 0 0; then ...
if whiptail --yesno "Is this OK?" 0 0; then ...
Run Code Online (Sandbox Code Playgroud)

  • 如果对话程序是可以接受的,难道`dialog` 或`whiptail` 不是更适合CLI 吗? (3认同)
  • 的确。添加到答案中。 (2认同)

gle*_*man 11

这对我来说看起来不错。我只会让它少一点“做或死”:

  • 如果“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
Run Code Online (Sandbox Code Playgroud)

根据@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
}
Run Code Online (Sandbox Code Playgroud)