看到树上有个例题是猜数字,虽然有代码,但是自己做一遍之后发现都是坑,作为一个一点Shell语法都不会的人,在敲完这个简单的例子之后收获了很多
代码如下
#!/bin/sh
num=$((RANDOM%61))
echo "The answer is $num"
echo "=================================="
input()
{
read -p "Please enter your number:" x #you need to input a blank before x
expr $x + 1 &>/dev/null #if x is a int, it can +1 sothat return 0, 0 restore in the $?
if [ $? -ne 0 ] #you need to input a blank after "if" and "["
then
echo "Please enter a int again"
input
fi
}
guess()
{
if [ $x -eq $num ];then #if "then" and "if" are in the same line, you need to input a ";"
echo "Guessed, you are clever!"
exit 0
elif [ $x -lt $num ];then
echo "too small"
input
else
echo "too large"
input
fi
}
main()
{
input
while true
do
guess
done
}
main
里面的注释就是我们爬过的一些主要的坑吧
操作系统是centos,在乌班图底下虽然能运行,但是结果有一些异常,比如随机数永远相同之类的,此时的random产生的是伪随机数,同时,判断是否是数字的操作也不相同