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

1
  • Try to figure out using the information from this question. If you still can't figure it out. edit your question with the new code, and write what errors you get, and / or what output you expect and what you get.
    – user68186
    Apr 30, 2020 at 19:16

1 Answer 1

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.

3
  • 1
    Thanks Sir, Problem Solved, :)
    – alvigee
    Apr 30, 2020 at 19:46
  • Just a one more thing, what if someone takes "invalid Option" can the script go back to the same question, demanding the answer in mentioned option, like 1 to 4 instead of writing any other number or alphabet?
    – alvigee
    Apr 30, 2020 at 19:51
  • @alvigee Yes, updated answer for that
    – Raffa
    Apr 30, 2020 at 20:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .