0

I'm creating a simple bash script

#!/bin/bash
echo "Q:1 What does CD command do? ************"
echo "  1)Change directory "
echo "  2)Change File"
echo "  3)Change OS"
echo "  4)None of the Above" 

read n
case $n in
  1) echo "correct answer";;
  2) echo "Wrong Answer";;
  3) echo "Wrong Answer";;
  4) echo "Wrong Answer";;
  *) echo "invalid option";;
esac

I will add 10 to 20 questions by repeating this code, what i want if any one one gives wrong or correct answer he will get total in the end by saying Correct Answer : ? and wrong Answer: ?, your total score is ??.. if any one can help. Thanks

Raffa
  • 34,963

1 Answers1

1

You could set two variables one for correct answer count and the other for wrong answer count with an initial value of zero then increment them. Also, you might want to use a while loop to ask for input again if an invalid value is interred like so:

#!/bin/bash

correct=0
wrong=0

echo "Q:1 What does CD command do? ************"
echo "  1)Change directory "
echo "  2)Change File"
echo "  3)Change OS"
echo "  4)None of the Above" 

while read n

do

case $n in
  1) echo "correct answer"; ((correct++)); break;;
  2) echo "Wrong Answer"; ((wrong++)); break;;
  3) echo "Wrong Answer"; ((wrong++)); break;;
  4) echo "Wrong Answer"; ((wrong++)); break;;
  *) echo "invalid option. Please try again"; ((wrong++));;
esac

done



echo "Q:1 What does SU command do? ************"
echo "  1)Change user "
echo "  2)Change File"
echo "  3)Change OS"
echo "  4)None of the Above" 

while read n

do

case $n in
  1) echo "correct answer"; ((correct++)); break;;
  2) echo "Wrong Answer"; ((wrong++)); break;;
  3) echo "Wrong Answer"; ((wrong++)); break;;
  4) echo "Wrong Answer"; ((wrong++)); break;;
  *) echo "invalid option. Please try again"; ((wrong++));;
esac

done

echo "$correct";
echo "$wrong";

The break will break the current while loop and move to the next question if 1,2,3 or 4 is provided as input or the loop will continue asking for input until a valid option is entered ie. 1,2,3, or 4

I think you'll find it easy to figure out the total score now.

Raffa
  • 34,963