Is there any default function/utility to prompt the user for yes/no in a Bash script?

Sometimes I need to ask the user for yes/no to confirm something.

Usually I use something like this:

# 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;
}

Is there a better way to do it? Is this utility maybe already in my /bin folder?


Solution 1:

Ah, there is something built-in: zenity is a graphical dialog program:

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

In addition to zenity, you can use one of:

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

Solution 2:

That looks fine to me. I would just make it a bit less "do or die":

  • if "Y" then return 0
  • if "N" then return 1

That way you can do something like:

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

With @muru's select suggestion, the function can be very terse:

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