“Yes/No” in Bash Script – Prompt for Confirmation

Very often in bash scrips you need to ask for user input that requires a Yes or No answer.

For example, you may want to put a quick “Are you sure?” prompt for confirmation before execution of some potentially dangerous part of a bash script.

In this article you’ll find three easiest and fastest ways to prompt for “Yes/No” confirmation in bash script.

Prompt To Continue In Bash

The best way to prompt for a confirmation to continue in a bash script is to use the read command (source):

read -p "Are you sure? " -n 1 -r
echo    # (optional) move to a new line
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
    exit 1
fi

Simple “Yes/No” Dialog In Bash

One of the most widely used method to ask user for a confirmation in a bash script is to combine read + case commands (source):

while true; do
    read -p "Do you wish to install this program?" yn
    case $yn in
        [Yy]* ) make install; break;;
        [Nn]* ) exit;;
        * ) echo "Please answer yes or no.";;
    esac
done

Select From “Yes/No” Menu In Bash

Another easy method is to use select command (source):

echo "Do you wish to install this program?"
select yn in "Yes" "No"; do
  case $yn in
    Yes ) make install;;
    No ) exit;;
  esac
done

5 Replies to ““Yes/No” in Bash Script – Prompt for Confirmation”

  1. Doesn’t work on bash 4.4

    Are you sure? read: arg count
    REPLY: Undefined variable.

  2. Svetoslav Slavchev says: Reply

    May be this will help other users:
    https://mike632t.wordpress.com/2017/07/06/bash-yes-no-prompt/

  3. The ‘select’ example is missing its done directive and so will throw an ‘unexpected end of file’ syntax error.

    The source linked to in that example has it correct: https://stackoverflow.com/a/226724/928062

    1. Thanks! Fixed.

  4. THANKS MAN!

Leave a Reply