shell运算符:算数,关系,布尔,字符串,文件测试
原生bash不支持简单的数学运算,可通过awk expr实现,expr最常用
expr是一款表达式计算工具,使用它能完成表达式的求值操作
示例如下:
1 val=` expr 2 + 2 ` 2 echo " Total value : ${val} "
注意
1.表达式和运算符之间要有空格
2.完整表达式要被``包含
算数运算符
示例如下: + - * / % == !=
1 a=10 2 b=20 3 4 val=` expr ${a} + ${b} ` 5 echo " a + b : ${val} " 6 7 val=` expr ${a} - ${b} ` 8 echo " a - b : ${val} " 9 10 val=` expr ${a} \* ${b} ` #乘号前必须加\才能实现惩罚运算# 11 echo " a * b : ${val}" 12 13 val=` expr ${b} / ${a} ` 14 echo " b / a : ${val} " 15 16 val=` expr ${b} % ${a} ` 17 echo " b % a : ${val} " 18 19 if [ ${a} == ${b} ] #条件语句写法,后续加入.此条件返回的是true or false,空格不能少# 20 then 21 echo " a is equal to b " 22 fi 23 24 if [ ${a} != ${b} ] 25 then 26 echo " a is not equal to b" 27 fi
关系运算符
关系运算符:只支持数字,不支持字符串,除非字符串的值是数字
关系运算符列表
1. -eq 检测两个数是否相等,返回true [ ${a} -eq ${b} ] equal
2. -ne 检测两个数是否相等,返回false [ ${a} -ne ${b} ] not euqal
3. -gt 检测左边是否大于右边,返回true [ ${a} -gt ${b} ] greater than
4. -lt 检测左边是否小于右边,返回false [ ${a} -lt ${b} ] less than
5. -ge 检测左边是否大于等于右边,返回true [ ${a} -ge ${b} ] greater or equal
6. -le 检测左边是否小于等于右边,返回false [ ${a} -le ${b} ] less or equal
示例如下:
1 a=10 2 b=20 3 if [ ${a} -eq ${b} ] 4 then 5 echo " a is equal to b " 6 else 7 echo " a is not equal to b " 8 fi
布尔运算符
布尔运算符列表
1. ! 非 [ !false ]
2. -o 或 [ ${a} -lt 20 -o ${b} -gt 100] a<20或b>100 返回true
3. -a 与 [ ${a} -lt 20 -a ${b} -gt 100] a<20并且b>100 返回true
示例如下:
1 a=10 2 b=110 3 4 if [ ${a} -lt 20 -a ${b} -lt 100 ] #a<20并且b<100# 5 then 6 echo " a<20或b<100成立!" 7 else 8 echo " 不成立! " 9 fi
字符串运算符
字符串运算符列表
1. = 检测两个字符串是否相等 [ ${a} = ${b} ]
2. != 检测两个字符串是否相等 [ ${a} = ${b} ]
3. -z 检测字符串长度是否为0,返回true [ -z ${a} ]
4. -n 检测字符串长度是否为0,返回false [ -n ${a} ]
5. str 检测字符串是否为空,不为空返回true [ ${a} ]
示例如下:
1 a="abc" 2 b="abc" 3 4 if [ ${a} = ${b} ] 5 then 6 echo " ${a} = ${b} : a is equal to b " 7 else 8 echo " ${a} = ${b} : a is not equal to b " 9 fi 10 11 if [ ${a} != ${b} ] 12 then 13 echo " ${a} != ${b} : a is not equal to b " 14 else 15 echo " ${a} != ${b} : a is equal to b " 16 fi 17 18 if [ -z ${a} ] 19 then 20 echo " -z ${a} : String length is zero " 21 else 22 echo " -z ${a} : String length is not zero " 23 fi 24 25 if [ -n ${b} ] 26 then 27 echo " -n ${b} : String length is not zero " 28 else 29 echo " -n ${b} : String length is zero" 30 fi