#!/bin/bash
# generate a random number between 1 and 100
number=$(( RANDOM % 100 + 1 ))
# set the maximum number of guesses
max_guess=5
# initialize the number of guesses
count=0
# main game loop
while true; do
# read the user's guess
read -p "Guess a number between 1 and 100 (or 'q' to quit): " guess
# check if the user entered 'q' to quit the game
if [[ "$guess" == "q" ]]; then
echo "Goodbye!"
exit 0
fi
# check if the user's guess is valid
if ! [[ "$guess" =~ ^[0-9]+$ ]]; then
echo "Invalid input. Please enter a number between 1 and 100."
continue
fi
# increment the number of guesses
count=$(( count + 1 ))
# check if the user's guess is correct
if [[ "$guess" -eq "$number" ]]; then
echo "You guessed it! The number was $number."
exit 0
elif [[ "$guess" -lt "$number" ]]; then
echo "Too low!"
else
echo "Too high!"
fi
# check if the user has used up all their guesses
if [[ "$count" -eq "$max_guess" ]]; then
echo "You have used up all your guesses. The number was $number."
exit 0
fi
done Write, Run & Share Bash code online using OneCompiler's Online Bash Shell for free. It's one of the robust, feature-rich Bash shell available over online and getting started with the OneCompiler's Bash Shell is simple and pretty fast. The editor shows sample boilerplate code when you choose language as Bash. OneCompiler also has reference scripts, where you can look for the sample scripts and start coding.
Bash (Bourne Again Shell) is a shell program written by Brian Fox and is an upgraded version of Bourne Shell program 'sh'.
name="Foo"
echo $name
echo "$name"
echo "${name}"
if [ conditional-expression ]
then
statements
fi
if [ conditional-expression ]
then
statements
else
statements
fi
if [ conditional-expression ]
then
statements
elif [ conditional-expression ]
then
statements
else
statements
fi