Step-by-Step Guide to Creating a Simple Bash Quiz Game
1. Create a Bash Script File
Open a terminal and create a new file for your script. You can use any text editor, such as nano or vim. For example:
nano quiz_game.sh
2. Write the Script
Paste the following script into your file. This script represents a basic quiz game where users answer multiple-choice questions.
#!/bin/bash
# Define questions and answers
questions=(
"What is the capital of France?"
"Which planet is known as the Red Planet?"
"What is the largest ocean on Earth?"
)
choices=(
"A. Berlin B. Madrid C. Paris D. Rome"
"A. Earth B. Mars C. Jupiter D. Saturn"
"A. Atlantic B. Indian C. Arctic D. Pacific"
)
answers=(
"C"
"B"
"D"
)
# Initialize score
score=0
# Iterate through questions
for i in "${!questions[@]}"; do
echo "Question $((i + 1)): ${questions[$i]}"
echo "${choices[$i]}"
read -p "Enter your choice (A, B, C, D): " user_answer
# Check if the answer is correct
if [ "$user_answer" == "${answers[$i]}" ]; then
echo "Correct!"
((score++))
else
echo "Incorrect. The correct answer was ${answers[$i]}."
fi
echo
done
# Show final score
echo "Quiz Over! Your final score is $score/${#questions[@]}."
3. Save and Exit
Save the file and exit the editor (Ctrl + X for nano, then Y to confirm and Enter).
4. Make the Script Executable
Change the file permissions to make the script executable:
chmod +x quiz_game.sh
5. Run the Script
Execute the script to play the quiz game:
./quiz_game.sh
Explanation of the Script
Define Questions, Choices, and Answers:
questions contains the quiz questions.
choices contains the possible answers for each question.
answers contains the correct answers corresponding to each question.
Score Initialization: score starts at 0 and will be incremented for each correct answer.
Loop Through Questions:
The for loop iterates over the questions array.
Displays the current question and the available choices.
Reads the user input and checks if it matches the correct answer.
Final Score Display: After all questions are answered, the final score is displayed.
Top comments (0)