Sat, 31 May 2025 20:19:04 +0530
Time to practice your Bash script and develop a simple game.
Exercise
Create a bash script that implements a number guessing game. The script should:
- Generate a random number between 1 and 100
- Allow the user to make guesses
- Provide feedback whether the guess is too high, too low, or correct
- Count the number of attempts
- Allow the user to play again after winning
The game should continue until the user guesses correctly, and then ask if they want to play another round.
๐ก Hints
- Use
$RANDOM
to generate random numbers - The modulo operator
%
can help limit the range - Use a
while
loop for the main game logic - Consider using a nested loop structure for replay functionality
- Input validation is important - check if the user enters a valid number
Test data
Test Case 1: Basic game flow
$ ./guessing_game.sh
Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.
Enter your guess: 50
Too low! Try again.
Enter your guess: 75
Too high! Try again.
Enter your guess: 62
Too low! Try again.
Enter your guess: 68
Congratulations! You guessed it in 4 attempts!
Do you want to play again? (yes/no): no
Thanks for playing! Goodbye!
Test Case 2: Input validation
$ ./guessing_game.sh
Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.
Enter your guess: abc
Invalid input! Please enter a number between 1 and 100.
Enter your guess: 150
Your guess must be between 1 and 100!
Enter your guess: 0
Your guess must be between 1 and 100!
Enter your guess: 42
Too high! Try again.
Test Case 3: Multiple rounds
$ ./guessing_game.sh
Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 100.
Enter your guess: 30
Congratulations! You guessed it in 1 attempts!
Do you want to play again? (yes/no): yes
Starting new game...
I'm thinking of a number between 1 and 100.
Enter your guess: 50
Too low! Try again.
Enter your guess: 60
Congratulations! You guessed it in 2 attempts!
Do you want to play again? (yes/no): no
Thanks for playing! Goodbye!
Solution 1: Basic implementaion
This is a straightforward implementation using nested while loops. The outer loop controls whether the player wants to play again, while the inner loop handles the guessing game logic. Key features:
- Uses
$RANDOM % 100 + 1
to generate numbers between 1-100 - Input validation with regex pattern matching
- Simple counter for tracking attempts
#!/bin/bash
# Number Guessing Game - Basic Implementation
# Main game loop
play_again="yes"
echo "Welcome to the Number Guessing Game!"
while [[ "$play_again" == "yes" ]]; do
# Generate random number between 1 and 100
secret_number=$((RANDOM % 100 + 1))
attempts=0
guessed=false
echo "I'm thinking of a number between 1 and 100."
echo
# Game loop for current round
while [[ "$guessed" == "false" ]]; do
# Read user input
echo -n "Enter your guess: "
read guess
# Validate input - check if it's a number
if ! [[ "$guess" =~ ^[0-9]+$ ]]; then
echo "Invalid input! Please enter a number between 1 and 100."
continue
fi
# Check if guess is in valid range
if [[ $guess -lt 1 || $guess -gt 100 ]]; then
echo "Your guess must be between 1 and 100!"
continue
fi
# Increment attempt counter
((attempts++))
# Check the guess
if [[ $guess -eq $secret_number ]]; then
echo "Congratulations! You guessed it in $attempts attempts!"
guessed=true
elif [[ $guess -lt $secret_number ]]; then
echo "Too low! Try again."
else
echo "Too high! Try again."
fi
done
# Ask if player wants to play again
echo
echo -n "Do you want to play again? (yes/no): "
read play_again
play_again=$(echo "$play_again" | tr '[:upper:]' '[:lower:]')
if [[ "$play_again" == "yes" ]]; then
echo
echo "Starting new game..."
fi
done
echo "Thanks for playing! Goodbye!"
Solution 2: Using functions
In this solution, I break down the game into modular functions, making the code more organized and reusable:
generate_random()
: Generates the secret numbervalidate_input()
: Handles all input validationplay_round()
: Contains the core game logicask_replay()
: Manages the replay promptmain()
: Orchestrates the overall game flow
#!/bin/bash
# Number Guessing Game - Function-based Implementation
# Function to generate random number
generate_random() {
echo $((RANDOM % 100 + 1))
}
# Function to validate input
validate_input() {
local input=$1
# Check if input is a number
if ! [[ "$input" =~ ^[0-9]+$ ]]; then
echo "Invalid input! Please enter a number between 1 and 100."
return 1
fi
# Check if number is in range
if [[ $input -lt 1 || $input -gt 100 ]]; then
echo "Your guess must be between 1 and 100!"
return 1
fi
return 0
}
# Function to play one round
play_round() {
local secret_number=$(generate_random)
local attempts=0
local guess
echo "I'm thinking of a number between 1 and 100."
echo
while true; do
# Get user input
echo -n "Enter your guess: "
read guess
# Validate input
if ! validate_input "$guess"; then
continue
fi
# Increment attempts
((attempts++))
# Check guess
if [[ $guess -eq $secret_number ]]; then
echo "Congratulations! You guessed it in $attempts attempts!"
break
elif [[ $guess -lt $secret_number ]]; then
echo "Too low! Try again."
else
echo "Too high! Try again."
fi
done
}
# Function to ask for replay
ask_replay() {
local response
echo
echo -n "Do you want to play again? (yes/no): "
read response
response=$(echo "$response" | tr '[:upper:]' '[:lower:]')
[[ "$response" == "yes" ]]
}
# Main program
main() {
echo "Welcome to the Number Guessing Game!"
while true; do
play_round
if ! ask_replay; then
break
fi
echo
echo "Starting new game..."
done
echo "Thanks for playing! Goodbye!"
}
# Run the main program
main
Solution 3: Enhanced version with difficulty levels
I added a few extra features:
- Difficulty levels with different number ranges
- Performance feedback based on attempts
- Hints when guesses are very far off
- Better user experience with clear menu options
#!/bin/bash
# Number Guessing Game - Enhanced Version with Difficulty Levels
# Function to display menu
show_menu() {
echo "Select difficulty level:"
echo "1. Easy (1-50)"
echo "2. Medium (1-100)"
echo "3. Hard (1-200)"
echo -n "Enter your choice (1-3): "
}
# Function to get range based on difficulty
get_range() {
case $1 in
1) echo 50 ;;
2) echo 100 ;;
3) echo 200 ;;
*) echo 100 ;; # Default to medium
esac
}
# Main game
echo "Welcome to the Number Guessing Game!"
echo
play_again="yes"
while [[ "$play_again" == "yes" ]]; do
# Select difficulty
show_menu
read difficulty
# Validate difficulty selection
if ! [[ "$difficulty" =~ ^[1-3]$ ]]; then
echo "Invalid choice! Using medium difficulty."
difficulty=2
fi
# Get range for selected difficulty
max_number=$(get_range $difficulty)
# Generate random number
secret_number=$((RANDOM % max_number + 1))
attempts=0
echo
echo "I'm thinking of a number between 1 and $max_number."
echo
# Game loop
while true; do
echo -n "Enter your guess: "
read guess
# Validate input
if ! [[ "$guess" =~ ^[0-9]+$ ]]; then
echo "Invalid input! Please enter a number."
continue
fi
if [[ $guess -lt 1 || $guess -gt $max_number ]]; then
echo "Your guess must be between 1 and $max_number!"
continue
fi
((attempts++))
# Check guess
if [[ $guess -eq $secret_number ]]; then
echo "Congratulations! You guessed it in $attempts attempts!"
# Give performance feedback
if [[ $attempts -le 5 ]]; then
echo "Excellent! You're a mind reader!"
elif [[ $attempts -le 10 ]]; then
echo "Good job! That was quick!"
else
echo "Well done! Practice makes perfect!"
fi
break
elif [[ $guess -lt $secret_number ]]; then
echo "Too low! Try again."
# Give hint for very far guesses
if [[ $((secret_number - guess)) -gt $((max_number / 4)) ]]; then
echo "(Hint: You're quite far off!)"
fi
else
echo "Too high! Try again."
# Give hint for very far guesses
if [[ $((guess - secret_number)) -gt $((max_number / 4)) ]]; then
echo "(Hint: You're quite far off!)"
fi
fi
done
# Ask for replay
echo
echo -n "Do you want to play again? (yes/no): "
read play_again
play_again=$(echo "$play_again" | tr '[:upper:]' '[:lower:]')
if [[ "$play_again" == "yes" ]]; then
echo
echo "Starting new game..."
echo
fi
done
echo "Thanks for playing! Goodbye!"
๐ Concepts to revise
The solutions discussed here use some terms, commands and concepts and if you are not familiar with them, you should learn more about them.
- Variables:
secret_number
,attempts
,guess
- Arithmetic operations:
$RANDOM % 100 + 1
, numeric comparisons - Conditional statements:
if/elif/else
for guess validation and checking - Loops:
while
loops, nested loops,continue
statement - Regular expressions:
[[ "$guess" =~ ^[0-9]+$ ]]
for number validation - Functions: Modular code organization (Solutions 2 & 3)
- Input/Output: read command,
echo
with-n
flag - String manipulation: tr command for case conversion
- Command substitution:
$(command)
syntax
๐ Further reading
If you are new to bash scripting, we have a streamlined tutorial series on Bash that you can use to learn it from scratch or use it to brush up the basics of bash shell scripting.

Recommended Comments