function initialize { num_ques=0 # Number of questions asked so far num_correct=0 # Number answered correctly so far cd ${QUIZDIR:=/usr/games/lib/quiz} || exit 2 } function choose_subj { subjects=$(\ls) PS3="Choose a subject for the quiz from the following: " select Subject in $subjects do if [[ -z "$Subject" ]] then echo "No subject chosen. Bye." >&2 exit 1 fi echo $Subject return 0 done } function exchange { temp_value=${questions[$1]} questions[$1]=${questions[$2]} questions[$2]=$temp_value } function scramble { set -A questions $(\ls) quescount=${#questions[*]} # Number of elements ((index=quescount-1)) while [[ $index > 0 ]] do ((target=RANDOM % index)) exchange $target $index ((index=index-1)) done } function ask { exec 3<$1 read -u3 ques || exit 2 read -u3 num_opts || exit 2 index=0 choices="" while [[ $index < $num_opts ]] do read -u3 next_choice || exit 2 choices="$choices:$next_choice" ((index=index+1)) done read -u3 correct_answer || exit 2 exec 3<&- SaveIFS="$IFS" IFS=":" choices=${choices#:} set $choices echo "You may press the Interrupt Key at any time to quit." PS3=$ques" " # Make $ques the prompt for select, but... # ...add some spaces for legibility. select answer do IFS="$SaveIFS" if [[ -z "$answer" ]] then echo Not a valid choice. Please choose again. elif [[ "$answer" = "$correct_answer" ]] then echo Correct! return 1 else echo No, the answer is $correct_answer. return 0 fi done } function summarize { if [[ $num_ques == 0 ]] then echo "You did not answer any questions" exit 0 fi ((percent=num_correct*100/num_ques)) print "You answered $num_correct questions correctly, out of \ $num_ques total questions." print "Your score is $percent percent." } # Main program initialize trap 'summarize ; exit 0' INT subject=$(choose_subj) [[ $? -eq 0 ]] || exit 2 cd $subject || exit 2 echo # Skip a line scramble for ques in ${questions[*]} do ask $ques result=$? ((num_ques=num_ques+1)) if [[ $result == 1 ]] then ((num_correct=num_correct+1)) fi echo # skip a line between questions sleep ${QUIZDELAY:=1} done summarize exit 0