bash数学运算
1.expr $num1 operator $num2
~$ num1=2~$ num2=4~$ expr $num1 > num2~$ expr $num1 \\> num20~$ expr $num1 + $num26~$ expr $num1 \\* $num28~$ expr $num1 % $num22~$ expr $num1 = $num20~$ expr $num1 != $num21~$ expr $num1 >= $num2expr: syntax error~$ expr $num1 \\>= $num20~$ expr $num1 \\<= $num21~$ expr $num1 \\| $num22~$ expr $num1 \\& $num22➜ shell
2.((((((num1 operator $num2))
~$ echo $((num1+num2))24~$ num1=2~$ echo $((num1+num2))6~$ echo $((num1-num2))-2~$ echo $((num1*num2))8~$ echo $((num1>num2))0~$ echo $((num1<num2))1#不准~$ echo $((num1&num2))0#不准~$ echo $((num1|num2))6~$ echo $((num1%num2))2#不准~$ echo $((num1=num2))4
**总结:**建议大家使用expr,因为其精准性比较高
练习
**需求描述:**提示用户输入一个正整数num,然后计算1+2+3+…+sum的值;必须对num是否为正整数做判断,不符合应当允许再次输入
#!/bin/bash#while truedoread -p \"pls input a positive number:\" num#判断变量是否为正整数#进行运算并将结果丢到垃圾桶里expr $num + 1 &> /dev/null#$?判断是否能够进行数学运算#可以$?!=0#不可以$?=0if [ $? -eq 0 ];thenif [ `expr $num \\> 0` -eq 1 ];thensum=0for((i=1;i<=$num;i++))dosum=`expr $sum + $i`doneecho \"1+2+3+...+$num = $sum\"exitelseecho \"error,input unlegal\"exitfifiecho \"input,echo enlegal\"done