“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"
case $yn in
    Yes ) make install;;
    No ) exit;;
esac
5 (1)
Article Rating (1 Votes)
Rate this article
Attachments
There are no attachments for this article.
Comments (1)
Comment By cellcore - Mon, Nov 30th, 2020 9:24 PM
awesome and straight to the point
Full Name
Email Address
Security Code Security Code
Related Articles RSS Feed
How to sort IP addresses in Linux
Viewed 2521 times since Thu, May 24, 2018
8 Practical Examples of Linux Xargs Command for Beginners
Viewed 4514 times since Fri, Jun 1, 2018
perl podstawy
Viewed 1488 times since Mon, May 21, 2018
10 Xargs Command Examples in Linux / UNIX
Viewed 2051 times since Fri, Jun 1, 2018
Display basic information about Physical Volumes
Viewed 2508 times since Sun, Jun 3, 2018
Using Shell Redirection: All About the Here-Doc
Viewed 9440 times since Wed, May 30, 2018
The Ultimate Bash Array Tutorial with 15 Examples
Viewed 11963 times since Sun, Sep 30, 2018
Bash: String Length – How To Find Out
Viewed 1612 times since Mon, Feb 18, 2019
Convert a human readable date to epoch with a shell script on OpenBSD and Mac OS X
Viewed 12604 times since Fri, May 25, 2018
10 Awk Tips, Tricks and Pitfalls
Viewed 5300 times since Wed, Aug 19, 2020