linux shell中实现猜数字游戏

 

1、

root@PC1:/home/test2# ls
test.sh
root@PC1:/home/test2# cat test.sh     ## 脚本
#!/bin/bash
ANSWER=$(expr $RANDOM % 100)
TIMES=0

echo "the range is 0-100, please guess."
while true
do
        read -p "please input your answer: " GUESS
        if [[ ! $GUESS =~ ^[0-9]+$ ]]
        then
                echo "please input an integer!"
                continue
        fi
        if [[ $GUESS -gt 100 || $GUESS -lt 0 ]]
        then
                echo "the range is 0-100! please try again!"
                continue
        fi
        let TIMES++
        if [ $GUESS -eq $ANSWER ]
        then
                echo "you are right!"
                echo "you have guess $TIMES time!"
                exit 0
        elif [ $GUESS -gt $ANSWER ]
        then
                echo "too big! please try again!"
        else
                echo "too small! please try again!"
        fi
done

 

2、测试

root@PC1:/home/test2# bash test.sh
the range is 0-100, please guess.
please input your answer: 60
too big! please try again!
please input your answer: abc
please input an integer!
please input your answer: 50
too big! please try again!
please input your answer: 400
the range is 0-100! please try again!
please input your answer: 30
too small! please try again!
please input your answer: 40
too big! please try again!
please input your answer: 35
too big! please try again!
please input your answer: 33
too small! please try again!
please input your answer: 34
you are right!
you have guess 7 time!

 

posted @ 2022-05-23 21:46  小鲨鱼2018  阅读(266)  评论(0编辑  收藏  举报