- 1、算术运算符
- 2、关系运算符
- 3、布尔运算符
- 4、逻辑运算符
- 5、字符串运算符
注:expr 是一款表达式计算工具,使用它能完成表达式的求值操作 ①、完整的表达式要被 ` ` 包含,注意这个字符不是常用的单引号,在 Esc 键下边 ②、运算符与表达式间要有空格
[root@ss]# cat test.sh #!/bin/bash a=10 b=20 #加法 ‘+’ c=`expr $a + $b` #减法 ‘-’ d=`expr $b - $a` #乘法 ‘*’ e=`expr $a * $b` #除法 ‘/’ f=`expr $b / $a` #除余 ‘%’ g=`expr $b % $a` echo "a+b: $c" echo "b-a: $d" echo "a*b: $e" echo "b/a: $f" echo "b%a: $g" a=$b echo "a: $a" h=10 #相等 ‘==’ if [ $a == $h ] then echo "ture" else echo "false" fi #不等于 ‘!=’ if [ $a != $h ] then echo "ture" else echo "false" fi [root@ss]# sh ./test.sh a+b : 30 b-a: 10 a*b: 200 b/a: 2 b%a: 0 a: 20 false ture2、关系运算符
关系运算符只支持数字,不支持字符串
①、‘eq’ 如果两个数相等,返回ture
②、‘-ne’ 如果两个数不相等,返回ture
③、‘-gt’ 如果左边数大于右边,返回ture
④、‘-lt’ 如果左边数小于右边,返回ture
⑤、‘-ge’ 如果左边数大于等于右边,返回ture
⑥、‘le’ 如果左边数小于等于右边,返回ture
[root@ss]# cat test.sh #!/bin/bash a=20 b=30 **#'eq' 如果两个数相等,返回ture** if [ $a -eq $b ] then echo "ture" else echo "false" fi #‘-ne’ 如果两个数不相等,返回ture if [ $a -ne $b ] then echo "ture" else echo "false" fi #‘-gt’ 如果左边数大于右边,返回ture if [ $a -gt $b ] then echo "ture" else echo "false" fi #‘-lt’ 如果左边数小于右边,返回ture if [ $a -lt $b ] then echo "ture" else echo "false" fi #‘-ge’ 如果左边数大于等于右边,返回ture if [ $a -ge $b ] then echo "ture" else echo "false" fi #‘le’ 如果左边数小于等于右边,返回ture if [ $a -le $b ] then echo "ture" else echo "false" fi [root@ss]# sh test.sh false ture false ture false ture3、布尔运算符
布尔运算与其他语言一致
①、!:非运算,非ture为false,非false为ture
②、-o :或运算,存在一个ture,返回ture,否则返回false
③、-a :与运算,存在一个false,返回false,否则返回ture
[root@ss]# cat test.sh #!/bin/bash a=30 b=50 if [ $a != $b ] then echo 'ture' else echo 'false' fi if [ $a -lt 50 -a $b -gt 20 ] then echo 'ture' else echo 'false' fi if [ $a -lt 50 -a $b -gt 60 ] then echo 'ture' else echo 'false' fi if [ $a -lt 50 -o $b -gt 20 ] then echo 'ture' else echo 'false' fi if [ $a -gt 50 -o $b -gt 20 ] then echo 'ture' else echo 'false' fi [root@ss]# sh test.sh ture ture false ture ture4、逻辑运算符
①、&&:逻辑的and
②、||:逻辑的or
[root@ss]# cat test.sh #!/bin/bash a=30 b=50 if [[ $a -lt 50 && $b -gt 20 ]] then echo 'ture' else echo 'false' fi if [[ $a -lt 50 && $b -gt 60 ]] then echo 'ture' else echo 'false' fi if [[ $a -lt 50 || $b -gt 20 ]] then echo 'ture' else echo 'false' fi if [[ $a -gt 50 || $b -gt 60 ]] then echo 'ture' else echo 'false' fi [root@ss]# sh test.sh ture false ture false5、字符串运算符
①、 =:字符串相等,返回ture
②、 !=:字符串不相等,返回ture
③、 -z:字符串长度为0,返回ture
④、 -n:字符串长度不为0,返回ture
⑤、 $:字符串不为空,返回ture
[root@ss]# cat test.sh #!/bin/bash a="qwe" b="abc" c="" if [ $a = $b ] then echo "ture" else echo "false" fi if [ $a != $b ] then echo "ture" else echo "false" fi if [ -z $c ] then echo "ture" else echo "false" fi if [ -n $b ] then echo "ture" else echo "false" fi if [ $c ] then echo "ture" else echo "false" fi [root@ss]# sh test.sh false ture ture ture false



