Bash is not really a preferable language to write high level applications. Its strengths are in interacting with system commands and automating stuff, not that much in implementing complex business logic or doing stuff like networking. You'd make your life easier by looking into a more appropriate language for this, like e.g. Python. Anyway, of course it's possible to do that with Bash, just more difficult, especially for a beginner.
So to get back to your actual question, yes, you can use the read
shell built-in to request user input and store it in shell variables, like:
read line
echo "You said <$line>"
Example run, including user input:
Hello there ← this is user input
You said <Hello there> ← this is the output
With these two commands, I first wait for one line of user input and store it in a variable I called $line
. Then I can output the variable again with the second command.
Type help read
to get a full description of the read
command and its available options.
You could use that in a loop to validate the input and keep asking until the answer is acceptable:
while [[ "$my_color" != "blue" && "$my_color" != "red" ]] ; do
read -p "Pick blue or red: " my_color
done
echo "You picked $my_color."
Example run, including user input:
Pick blue or red: green
Pick blue or red:
Pick blue or red: red
You picked red.
There are more elegant ways to write menus which provide you a choice between a number of predefined options though, e.g. using select
. See How can I create a select menu in a shell script? for more info about that.