How to use a while loop to write a small script?

Use of such an interactive script format while loop written in the shell, a and b are integers equal to a required error prompted:

a-b=?

a+b=?

a*b=?

a/b=?

a**b=?

a%b=?

Solution: First, we analyze the meaning of the questions, the output of plus or minus two integer multiplication and division of power to take over the results, asked not to be understood as being given only enter two integers, ready go!

while true
#循环一直为真
do
    read -t 5 -p '请输入2个整数:' a b
    #用read读ab两个数并提示,5秒未输入即超时
    if [[ -z "$b" ]]; then
    #如果$b长度为空,就代表没有输入就echo提示
        echo '请输入2个整数'
        continue
        #结束当次循环,继续下一次循环
    fi
    expr 10 + $a + $b &>/dev/null
    #用10加$a和$b结果输出到空
    if [[ $? -ne 0 ]]; then
    #如果$a和$b加10的结果有问题,那么返回值就不等于0代表有问题,提示echo
        echo '只能输入2个整数'
        continue 
        #又结束本次循环,继续下一次循环
        #到这里我们的判断就完成了,所以只有输入2个整数才能继续进行运算
    fi
    echo "a-b=$(($a-$b))"
    echo "a+b=$(($a+$b))"
    echo "a*b=$(($a*$b))"
    echo "a/b=$(($a/$b))"
    echo "a**b=$(($a**$b))"
    echo "a%b=$(($a%$b))"
done

Scripts can be used to copy and paste

[root@node1]# sh test.sh
请输入2个整数:1 2
a-b=-1
a+b=3
a*b=2
a/b=0
a**b=1
a%b=1
请输入2个整数:10 23
a-b=-13
a+b=33
a*b=230
a/b=0
a**b=200376420520689664
a%b=10
请输入2个整数:12 2只能输入2个整数
请输入2个整数:
a-b=10
a+b=14
a*b=24
a/b=6
a**b=144
a%b=0
请输入2个整数:^C
[root@node1]# 

I can see has been tested successfully!

Guess you like

Origin blog.51cto.com/14573101/2447069