一、数值运算与运算符
1.1数值运算
1.1.1 declare 声明变量类型
语法:
declare [+/-] [选项] 变量名
选项:
-:给变量设定类型属性
+:取消变量类型属性
-i:将变量声明为整型
-x:将变量声明为环境变量(“export 变量名”也可以设置为环境变量)
-p:显示指定变量被声明的类型
示例1:
vim param4.sh
#!/bin/bash
aa=11;
bb=22;
cc1=$aa+$bb;
echo "cc1 的值:$cc1"
declare -i cc2=$aa+$bb;
echo "cc2 的值:$cc2"
结果:
chenzhitaodeMacBook-Pro:shell chenzhitao$ ./param4.sh
cc1 的值:11+22
cc2 的值:33
1.1.2使用expr 或者let 数值运算工具
示例:
#!/bin/bash
aa=11;
bb=22;
# 注意 + 运算符两边一定要有空格
cc1=$(expr $aa+$bb);
echo "cc1 is $cc1";
cc2=$(expr $aa + $bb);
echo "cc2 is $cc2";
结果:
chenzhitaodeMacBook-Pro:shell chenzhitao$ ./param5.sh
cc1 is 11+22
cc2 is 33
1.1.3 "$((运算表达式))"或者"$[运算表达式]"
示例:
#!/bin/bash
aa=11;
bb=22;
cc1=$(($aa+$bb));
cc2=$[$aa + $bb];
echo "cc1 is $cc1";
echo "cc2 is $cc2";
结果:
chenzhitaodeMacBook-Pro:shell chenzhitao$ ./param6.sh
cc1 is 33
cc2 is 33
1.2运算符
数值越大,优先级越高: