原本书上这个例子是教调试脚本的,它故意给出的脚本中有几个错误,教我们认识系统提示的错误,并修改运行。但比较难写出来,所以把修改好了的脚本放上来,这个脚本比较有趣味的
#!/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)整个脚本并不复杂,但逻辑清晰明了,也很有意思。