I would like to write a simple bash script for training multiple choice tests. Ask one question; give four choices (a, b, c, d); if user enters input, show if it is wrong or right and continue with the next question.
Here is my code so far:
#!/usr/bin/bash
echo Question1="How much is 2 2?"
echo a="1"
echo b="2"
echo c="3"
echo d="4"
read Question1
if [ "$Question1" = "d" ];
then
echo "this is correct"
else
echo "this is NOT correct"
fi
All samples about the read
command example I found so far on youtube etc. stop after one question. How can I ask multiple questions? Entering another question does not work and bash shows a syntax error:
#!/usr/bin/bash
echo Question1="How much is 2 2?"
echo a="1"
echo b="2"
echo c="3"
echo d="4"
read Question1
if [ "$Question1" = "d" ];
then
echo "this is correct"
else
echo "this is NOT correct"
echo Question2="How much is 2 1?"
echo a="1"
echo b="2"
echo c="3"
echo d="4"
read Question2
if [ "$Question2" = "c" ];
then
echo "this is correct"
else
echo "this is NOT correct"
fi
CodePudding user response:
It is giving you a syntax error because you don't have a fi
after your first if
statement, probably an error during copy/pasting.
Afterwards it should work fine.
CodePudding user response:
This is where the select
command is handy
PS3="How much is 2 2? "
select choice in 1 2 3 4; do
if [[ $choice == 4 ]]; then
echo "Correct"
break
fi
echo "Incorrect"
done
PS3="How much is 2 1? "
select choice in 1 2 3 4; do
if [[ $choice == 3 ]]; then
echo "Correct"
break
fi
echo "Incorrect"
done
Or, we can encapsulate the repetition in a function:
question() {
local PS3="$1 " answer=$2 choice
shift 2
select choice in "$@"; do
if [[ $choice == "$answer" ]]; then
echo "Correct"
break
fi
echo "Incorrect"
done
}
question "How much is 2 2?" 4 1 2 3 4
question "How much is 2 1?" 3 1 2 3 4