出于项目需要,需要用脚本执行计算
最简单的方法1:$((这里写算式,可以写变量))
~/Desktop$ cat test.sh
a=102
c=$((a + 123))
echo a: $a
echo \$\(\(a + 123\)\): $c
~/Desktop$ ./test.sh
a: 102
$((a + 123)): 225
最简单的方法2:$[这里写算式]
~/Desktop$ cat ./test.sh
a=102
c=$[a + 123]
echo a: $a
echo \$\[a + 123\]: $c
~/Desktop$ ./test.sh
a: 102
$[a + 123]: 225
另外还有命令行的方式:declare和expr
declare -i的方式,后面的算式不能有空格,有空格相当于新的参数
~/Desktop$ cat ./test.sh
a=102
declare -i c=$a+123
echo a: $a
echo declare -i \$a + 123: $c
~/Desktop$ ./test.sh
a: 102
declare -i $a + 123: 225
####加个空格
~/Desktop$ vi ./test.sh
~/Desktop$ cat ./test.sh
a=102
declare -i c=$a +123
echo a: $a
echo declare -i \$a + 123: $c
~/Desktop$ ./test.sh
./test.sh: 第 2 行:declare: “+123”: 不是有效的标识符
a: 102
declare -i $a + 123: 102
expr的方式:
~/Desktop$ cat test.sh
a=102
c=$(expr $a + 123)
echo a: $a
echo expr \$a + 123: $c
~/Desktop$ ./test.sh
a: 102
expr $a + 123: 225
注意:$(())是计算,$()是执行命令
另:计算数值后进行比较
比较:
1、-gt:大于,greater than。
2、-eq:等于,equal。
3、-lt:小于,less than。
4、-ge:大于等于,greater than or equal。
5、-le:小于等于,less than or equal。
6、-ne:不等于,not equal。
多个条件:
1、-a:且,and。
2、-o:或,or。
多个条件:
1、&&:用来执行条件成立后执行的命令。
2、||:用来执行条件不成立后的执行命令。
单个条件:
~/Desktop$ cat test.sh
a=102
c=$(expr $a + 123)
echo a: $a
echo expr \$a + 123: $c
# 比较
if [ $a -gt 200 ]; then
echo \$a = $a \> 200
elif [ $a -gt 100 ]; then
echo \$a = $a \> 100
else
echo \$a = $a \<= 100
fi
# -a连接符
if [ $a -gt 100 -a $c -le 225 ]; then
echo aaaa match 100 - 225
fi
# || 逻辑运算符
if [ $a -ge 123 ] || [ $c -gt 225 ]; then
echo oror match 123 225;
else
echo oror not match a ge 123 and c gt 225
fi
if [ $a -ge 102 ] || [ $c -gt 555 ]; then
echo oror match a ge 102 or c gt 555;
else
echo oror not match a ge 102 and c gt 555
~/Desktop$ ./test.sh
a: 102
expr $a + 123: 225
$a = 102 > 100
aaaa match 100 - 225
oror not match a ge 123,c gt 225
oror match a ge 102 or c gt 555
注意if[]中的-a要放在[]里面连接多个比较,并且[]前后里外都要有空格,