How to prompt and read user input in Bash

Tutorial Difficulty Level    

If we would like to ask the user for input then we use a command called read in our bash scripts. This command takes the input and will save it into a variable.

Here are two slightly different versions of the same shell script. This first version prompts the user for input only once, and then dies if the user doesn’t give a correct Y/N answer:

This second version stays in a loop until the user supplies a Y/N answer:

This Linux Bash ‘read’ function is nice, because it does both things, prompting the user for input, and then reading the input. We prefer the second approach, but thought we’d share both of them here. They are subtly different, but note the extra break in the first script.