Skip to content

Instantly share code, notes, and snippets.

@ravikant-pal
Created July 12, 2025 09:58
Show Gist options
  • Save ravikant-pal/ed873f0f3008713b2a38555d12c55921 to your computer and use it in GitHub Desktop.
Save ravikant-pal/ed873f0f3008713b2a38555d12c55921 to your computer and use it in GitHub Desktop.
🎲 Number Guessing Game β€” Bash Scripting Activity

🎲 Number Guessing Game β€” Bash Scripting Activity

⏱ Duration: 40 minutes

🧰 Tools: Bash, if, while, case, $RANDOM, I/O operations


🎯 Objective

Build an interactive CLI game in Bash that:

  • Randomly generates a number between 1 and 20
  • Prompts the user to guess it
  • Gives feedback: β€œToo high”, β€œToo low”, or β€œCorrect!”
  • Continues prompting until guessed right
  • Handles invalid input gracefully

πŸ›  Expected Script Behavior

Here’s what your script (guess_number.sh) should do:

#!/bin/bash

# 🎲 Generate random number between 1 and 20
TARGET=$((RANDOM % 20 + 1))
TRIES=0

echo "Welcome to the Number Guessing Game! 🎯"
echo "Guess a number between 1 and 20:"

while true; do
  read -p "Your guess: " GUESS

  # Validate input: is it a number?
  case $GUESS in
    ''|*[!0-9]*) echo "β›” Please enter a valid number!" && continue ;;
  esac

  ((TRIES++))

  if [ "$GUESS" -eq "$TARGET" ]; then
    echo "πŸŽ‰ Correct! The number was $TARGET. You guessed it in $TRIES tries."
    break
  elif [ "$GUESS" -lt "$TARGET" ]; then
    echo "πŸ“‰ Too low! Try again."
  else
    echo "πŸ“ˆ Too high! Try again."
  fi
done

βœ… Key Concepts Practiced

Bash Feature What it Does
$RANDOM Generates pseudo-random numbers
if-elif-else Branch logic for comparing guesses
while true Loop until correct guess is made
read -p User input in interactive mode
case Validate input format (numeric check)

πŸ’‘ Optional Enhancements

  • Limit max attempts to 5 and end game if not guessed
  • Add color to terminal using ANSI codes
  • Track best scores in a file (local leaderboard)
  • Make difficulty levels: easy (1–10), hard (1–100)

🧠 Discussion Points

Topic Industry Relevance
Loops & input validation Building CLI tools & setup wizards
Case conditions Robust error handling in scripts
Random number generation Testing, simulation, automation

🏁 Sample Output

Welcome to the Number Guessing Game! 🎯
Guess a number between 1 and 20:
Your guess: 10
πŸ“ˆ Too high! Try again.
Your guess: 7
πŸ“‰ Too low! Try again.
Your guess: 8
πŸŽ‰ Correct! The number was 8. You guessed it in 3 tries.

β€œCode is like a game β€” you just need the right logic to win.” πŸ’‘

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment