1. Guess the number game
- Get a random number in a specified range and store it in a variable
- Prompt the user to guess the number, guess the right one, and continue with the wrong guess until the right guess
- And set the number of guesses, and exit after the number is exhausted
2. The script content is written as follows
#!/bin/bash
num=$[$RANDOM%10+1]
time=5
while :
do
echo "你还有$time次猜的机会"
if [ $time -eq 0 ];then
echo "猜的机会用完了,正在退出...."
break
fi
read -ep "请输入猜的数字:" guess_num
if [ $guess_num -gt $num ];then
echo "猜大了"
elif [ $guess_num -lt $num ];then
echo "猜小了"
else
echo "猜对了"
break
fi
let time--
done
3. Add execution permissions to the script
chmod +x guess_num.sh
4. Execute script test
[root@host-137 ~]# sh guess_num.sh
你还有5次猜的机会
请输入猜的数字:2
猜大了
你还有4次猜的机会
请输入猜的数字:5
猜大了
你还有3次猜的机会
请输入猜的数字:7
猜大了
你还有2次猜的机会
请输入猜的数字:9
猜大了
你还有1次猜的机会
请输入猜的数字:2
猜大了
你还有0次猜的机会
猜的机会用完了,正在退出....