I’m learning bash-scripting, and am in the process of building a “quiz app”, which is supposed to pick a random question from a json file of questions, display the possible answers, let me pick an answer from 1 to 4 and write if I’ve chosen correctly.
As far as I can tell, I’ve followed every step the teacher made, but what I’m getting is:
QUESTION
1) ANSWER 1
ANSWER 2
ANSWER 3
ANSWER 4
Also, pressing any number, which is supposed to send the corresponding answer to verify if it’s correct, always gives me the message that this is not correct.
Here is my code:
#!/usr/bin/env bash
load_question() {
local contents
local qtotal
local qrandom
local question
contents=$(cat ./questions.json)
qtotal=$(echo "${contents}" | jq '.results | length')
(( qrandom = RANDOM % qtotal ))
question=$(echo "${contents}" | jq ".results[${qrandom}]")
echo "${question}" | jq -r ".question"
echo "${question}" | jq -r ".correct_answer"
echo "${question}" | jq -r ".incorrect_answers[0]"
echo "${question}" | jq -r ".incorrect_answers[1]"
echo "${question}" | jq -r ".incorrect_answers[2]"
}
ask_question() {
local question="$1"
local correct_answer="$2"
local incorrect_answer_0="$3"
local incorrect_answer_1="$4"
local incorrect_answer_2="$5"
local answers
answers=$(echo -e "${correct_answer}n${incorrect_answer_0}n${incorrect_answer_1}n${incorrect_answer_2}" | sort -R)
echo "${question}"
IFS=$'n'
select answer in "${answers}"; do
if [[ "${answer}" == "${correct_answer}" ]]; then
echo "You got it!"
return 0
else
echo "This ain't it, chief!"
return 1
fi
done
}
main() {
local question
local correct_answer
local incorrect_answer_0
local incorrect_answer_1
local incorrect_answer_2
{
read -r question
read -r correct_answer
read -r incorrect_answer_0
read -r incorrect_answer_1
read -r incorrect_answer_2
} < <(load_question)
ask_question "${question}"
"${correct_answer}"
"${incorrect_answer_0}"
"${incorrect_answer_1}"
"${incorrect_answer_2}"
}
main "$@"
Tried to copy the teacher’s final code.
A.H. is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.