(一)算数运算符:
1、运算符介绍
+,-
*,/,%
**:幂运算,最先计算。
++,--
!,&&,||
<,>,<=
==,!=,=
<<,>>:向左,右移位。
~,|,&,^:按位取反,按位异或,按位与,按位或
=,+=,-=,*=,/=,%=
(二)编程常见运算命令
1、只适合整数
①(())
[root@centos6-kvm3 ~]# i=$a+1
[root@centos6-kvm3 ~]# echo $i
1+1
[root@centos6-kvm3 ~]# echo $((a+3))
4
[root@centos6-kvm3 ~]# echo $((2**3))
8
[root@centos6-kvm3 ~]# echo $((1+2**3-5%3))
7
[root@centos6-kvm3 ~]# ((i++))
[root@centos6-kvm3 ~]# echo $i
3
②let
[root@centos6-kvm3 ~]# a=1
[root@centos6-kvm3 ~]# i=$a+1
[root@centos6-kvm3 ~]# let i=$a+1
[root@centos6-kvm3 ~]# echo $i
2
③expr
[root@centos6-kvm3 ~]# expr 2 + 3
5
[root@centos6-kvm3 ~]# expr 2*2
2*2
[root@centos6-kvm3 ~]# expr 2 * 2
expr: syntax error
[root@centos6-kvm3 ~]# expr 2 \* 2
4
④$[]
[root@centos6-kvm3 ~]# echo $[2-3]
-1
[root@centos6-kvm3 ~]# echo $[1+3]
4
2、既适合整数,又适合小数:
①bc
[root@centos6-kvm3 ~]# bc
1+2
3
2-1
1
[root@centos6-kvm3 ~]# echo 1.1+2| bc
3.1
②awk
[root@centos6-kvm3 ~]# echo 2.1 1.4| awk '{print $1*$2}'
2.94
[root@centos6-kvm3 ~]# echo 2.1 1.4| awk '{print $1-$2}'
0.7
(三)expr的企业级实战案例详解
1、判断一个是否为整数:
[root@centos6-kvm3 ~]# expr 2 + 3
5
[root@centos6-kvm3 ~]# expr 2 + a
expr: non-numeric argument
[root@centos6-kvm3 ~]# echo $?
2
[root@centos6-kvm3 ~]# a=2
[root@centos6-kvm3 ~]# expr 2 + $a &>/dev/null
[root@centos6-kvm3 ~]# echo $?
0
[root@centos6-kvm3 ~]# a=oldboy
[root@centos6-kvm3 ~]# expr 2 + $a &>/dev/null
[root@centos6-kvm3 ~]# echo $?
2
[root@centos6-kvm3 ~]#
判断参数是否为整数应用脚本:
[root@centos6-kvm3 scripts]# cat judge.sh
#!/bin/bash
expr 2 + $1 &>/dev/null
if [ $? -eq 0 ]
then
echo "$1 is 整数"
else
echo "$1 is not 整数"
fi
[root@centos6-kvm3 scripts]# sh judge.sh 4
4 is 整数
[root@centos6-kvm3 scripts]# sh judge.sh j
j is not 整数
[root@centos6-kvm3 scripts]#
2、expr判断文件扩展名:
[root@centos6-kvm3 scripts]# cat judge1.sh
#!/bin/bash
expr "$1" : ".*\.txt" &>/dev/null
if [ $? -eq 0 ]
then
echo "$1 is 文本"
else
echo "$1 is not 文本"
fi
[root@centos6-kvm3 scripts]# sh judge1.sh old.txt
old.txt is 文本
[root@centos6-kvm3 scripts]# sh judge1.sh old.log
old.log is not 文本
[root@centos6-kvm3 scripts]#
3、expr计算字符串长度:
[root@centos6-kvm3 scripts]# oldboy="i am oldboy"
[root@centos6-kvm3 scripts]# echo ${#oldboy}
11
[root@centos6-kvm3 scripts]# expr length "$oldboy"
11
[root@centos6-kvm3 scripts]#
|
|