101个shell脚本 猜数字游戏代码
原本书上这个例子是教调试脚本的,它故意给出的脚本中有几个错误,教我们认识系统提示的错误,并修改运行。但比较难写出来,所以把修改好了的脚本放上来,这个脚本比较有趣味的
#!/bin/sh # hilow -- A simple number-guessing game biggest=100 # maximum number possible guess=0 # guessed by player guesses=0 # number of guesses made number=$(($$ % $biggest)) # random number, between 1 and $biggest while [ $guess -ne $number ] do echo -n "Guess? " ; read guess if [ "$guess" -lt $number ] ; then echo "... bigger!" elif [ "$guess" -gt $number ] ; then echo "... smaller!i" fi guesses=$(($guesses + 1)) done echo "Right!! Guessed $number in $guesses guesses." exit 0
脚本分析
#1) number=$(($$ % $biggest)) $$代表执行此shell的pid,因为每次执行shell的pid并不相同, 所以number为1-100的随机数。
#2)$guess -ne $number ,if [ "$guess" -lt $number ],elif [ "$guess" -gt $number ] ;为判断输入的数字与$number的比较。
#3)整个脚本并不复杂,但逻辑清晰明了,也很有意思。
相关推荐
huha 2020-10-16
laisean 2020-11-11
大牛牛 2020-10-30
firefaith 2020-10-30
liguojia 2020-10-20
wangzhaotongalex 2020-10-20
以梦为马不负韶华 2020-10-20
JohnYork 2020-10-16
Julyth 2020-10-16
applecarelte 2020-10-16
laisean 2020-09-27
flycappuccino 2020-09-27
liguojia 2020-09-27
wangzhaotongalex 2020-09-22
流年浅滩 2020-10-23
liujianhua 2020-10-22
woaimeinuo 2020-10-21
tufeiax 2020-09-03
laisean 2020-09-01
vvu 2020-09-16
libao 2020-09-16
Yyqingmofeige 2020-08-18
zhushixia 2020-08-17