Hello, in this article we will look at simple shell number game. The purpose of the game is demonstrate simple shell scripting commands like if, while, user input-output and etc.
When script execute firstly, it generates random number between 1 and 100 and it asks for user to enter “Number of attempts he/she wish to try”. Then in the while loop we get user’s number and check it with computer’s random number. We will exit loop when user reached his maximum attempts or when he found number.
I think it is very useful for beginners which they are learning bash scripting.
You will analyse script below or in github https://github.com/sevdimali/numbergame
#!/bin/bash # Author: Sevdimali Isayev # Create date: 15/02/2017 # Description: Purpose of the game to help new shell learners to better understand # variable declarations, if, while, user input-output and other commands. chck=0 mycount=0 rndnum=$((1 + RANDOM % 100)) echo "---------------------------------------------------" echo "- _____ __ ______ -" echo "- ___ | / /___ ________ ______ /______________ -" echo "- __ |/ /_ / / /_ __ __ \_ __ \ _ \_ ___/ -" echo "- _ /| / / /_/ /_ / / / / / /_/ / __/ / -" echo "- /_/ |_/ \__,_/ /_/ /_/ /_//_.___/\___//_/ -" echo "- -" echo "- _______ _______ __ __ _______ -" echo "- | || _ || | | || | -" echo "- | ___|| |_| || |_ | || ___| -" echo "- | | __ | || || |___ -" echo "- | || || _ || || ___| -" echo "- | |_| || | | || ||_|| || |___ -" echo "- |_______||__| |__||_| |_||_______| -" echo "---------------------------------------------------" echo "" echo "Please enter number of attempts you wish to try:" read ua_count if [ $ua_count -le 0 ]; then echo "Bye Bye, You entered invalid number" sleep 1 exit fi while [ $chck -ne 1 ] do echo "Number:" read usernum if [ $usernum -eq $rndnum ]; then echo "Congratulations!!" echo "You found it within $mycount attempts." chck=1 fi if [ $usernum -lt $rndnum ]; then echo "Less than Computer's number" fi if [ $usernum -gt $rndnum ]; then echo "Greater than Computer's Number" fi if [ $ua_count -eq $mycount ]; then echo "You lost all of your chances, bye bye :))" chck=1 fi mycount=$((mycount+1)) done