How to show interactive YES/NO prompt in Bash
In Category Bash
The Bash shell provides an in-built command “read” to read a line from the standard input. The following sample script prompts user to provide his answer as either “yes” or “no“.
[neo@techpulp ~]# cat yesno.sh #!/bin/bash echo -n "Do you like blue color (yes/no)? " read color if [ "$color" == "yes" ]; then echo "YES: That's great. I like blue color too." else echo "NO: Never mind." fi [neo@techpulp ~]#
In the above script “echo -n” is used to print the prompt message to keep the cursor in the same line. Here is what happens when the script is run and different answers are given.
[neo@techpulp ~]# sh yesno.sh Do you like blue color (yes/no)? yes YES: That's great. I like blue color too. [neo@techpulp ~]# [neo@techpulp ~]# sh yesno.sh Do you like blue color (yes/no)? no NO: Never mind. [neo@techpulp ~]#
The above script expects only two choices from the user. However it can be changed to expect any number of options. For example, the following script prompts the user with three choices.
[neo@techpulp ~]# cat multi-chose.sh #!/bin/bash echo -n "Which color you like the most (red/green/blue)? " read color case "$color" in red) echo You have chosen red ;; green) echo You have chosen green ;; blue) echo You have chosen blue ;; *) echo Invalid option selected ;; esac [neo@techpulp ~]#
You can read this article to learn more about combining “echo” and “read” commands in to one command. It also contains information about setting a time out value for the user input.
Great tutorial, I only draw but will pass your post address to my programmer. He will love it. Thanks for sharing.
Regards,
Matt Kolorowanki,
Illustrator