Thursday, 9 April 2020

Bash script to guess a random one-digit number

Script to guess a random one-digit number

$ vi ch4_solution.sh game

#!/bin/bash
rand=$RANDOM
secret=${rand:0:1}

function game {
        read -p "Guess a random one-digit number! " guess
        while [[ $guess != $secret ]]; do
                read -p "Nope, try again! " guess
        done
        echo "Good job, $secret is it! You're great at guessing!"
}

function generate {
        echo "A random number is: $rand"
        echo -e "Hint: type \033[1m$0 game\033[0m for a fun diversion!"
}

if [[ $1 =~ game|Game|GAME ]]; then
        game
else
        generate
fi

$ ./ch4_solution.sh game
Guess a random one-digit number! 1
Nope, try again! 4
Nope, try again! 5
Good job, 5 is it! You're great at guessing!

No comments:

Post a comment