Last active
August 29, 2015 14:24
-
-
Save afonsomatos/2c02fce8c11bfc026211 to your computer and use it in GitHub Desktop.
Quiz in bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Try to guess number | |
# Function that generates numbers based on range | |
function random { | |
num=$(($RANDOM%$1+1)) | |
echo $num | |
} | |
function noargs { | |
echo "Error: Invalid flag specified"; | |
} | |
# Number of guesses | |
guesses=3 | |
# Range of random number | |
range=10 | |
# Check for special flags | |
while getopts :g:r: option; do | |
case option in | |
g) guesses=$OPTARG;; | |
r) range=$OPTARG;; | |
*) | |
noargs | |
exit 1;; | |
esac | |
done | |
# Generate random number | |
num=$(random $range) | |
# The number input | |
read -p "Guess number 1-$range: " inp | |
while [[ inp -ne num && --guesses -gt 0 ]]; do | |
read -p "Wrong number, you have $guesses tries left: " inp | |
done | |
# Check if the user got it | |
if [[ inp -eq num ]]; then | |
echo "Congratulations! You have won, number was: $num" | |
else | |
echo "Oh no! You have lost the game! Number was: $num" | |
fi | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment