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
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
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) |
- 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)
Topic | Industry Relevance |
---|---|
Loops & input validation | Building CLI tools & setup wizards |
Case conditions | Robust error handling in scripts |
Random number generation | Testing, simulation, automation |
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.β π‘