shell编程中变量的运算 (shell 06)

主要包括以下3种

字符串操作
数学运算
浮点运算

一.字符串操作
字符串的连接
连接字2个字符串不需要任何连接符,挨着写即可

长度获取
  expr length "hello"
  expr length "$str" 变量名必须放在双引号里,否者语法错误
查找字符串中字符的位置
  expr index "$str" CHARS
  第一个是从1 开始的,查找不到返回 0 ,返回匹配到的第一个字符的位置

[root@localhost110 ~]# echo $str
hello word
[root@localhost110 ~]# expr index "$str" h
1
[root@localhost110 ~]# expr index "$str" hel (只匹配h)
1
[root@localhost110 ~]# expr index "$str" a
0

字符串截断
expr substr "$str" POS LENGTH
POS起始位置(包含),LENGTH 长度

[root@localhost110 ~]# expr substr "$str" 7 4
word

字符串匹配
expr "$str" : REGEXP (冒号前后都得有空格)
expr mathch "$str" REGEXP
必须完整匹配才行

[root@localhost110 ~]# echo $str
aBcD phP2016ajax
[root@localhost110 ~]# expr "$str" : '([a-z]* [a-z]*)'
aBcD phP

expr运算

http://www.cnblogs.com/HKUI/articles/6548798.html

二.数学运算
逻辑运算
数值运算

逻辑运算
&,|,<,>,=,!=,<=,>=
数值运算
+,-,*,/,%

expr expression
result=$[expression]

[root@localhost110 sh]# echo $num1,$num2,$num3
1,2,1
[root@localhost110 sh]# expr $num1<$num2
-bash: 2: 没有那个文件或目录

操作符两边 要有空格

[root@localhost110 sh]# expr $num1<$num2 
1<2
[root@localhost110 sh]# expr $num1 < $num2
1
[root@localhost110 sh]# expr $num1 = $num3
1
[root@localhost110 sh]# expr $num1 = $num2
0
expr中用=判断是否等
在[]中==

[root@localhost110 sh]# res=$[$num1=$num3]
-bash: 1=1: attempted assignment to non-variable (error token is "=1")
[root@localhost110 sh]# res=$[$num1==$num3]
[root@localhost110 sh]# echo $res
1
数字运算
[root@bogon sh]# a=1;b=2;c=$a+$b;echo $c;
1+2
[root@bogon sh]# a=1;b=2;c=[$a+$b];echo $c;
[1+2]
[root@bogon sh]# a=1;b=2;c=$[$a+$b];echo $c;
3
[root@bogon sh]# a=1;b=2.5;c=$[$a+$b];echo $c;
-bash: 1+2.5: 语法错误: 无效的算术运算符 (错误符号是 ".5")
[root@bogon sh]# a=1;b=2.10;c=`echo $a+$b|bc`
[root@bogon sh]# echo $c
3.10
View Code

浮点数运算
内建计算器 bc
bc能够识别:
数字(整型和浮点型)
变量
注释 (以 #开始的行 或者/* */)
表达式
编程语句 (如条件判断 :if-then)
函数

bc -q 能忽略版本信息等提示语
scale可设置精度

[root@localhost110 sh]# bc -q
10/3
3
scale=4
10/3
3.3333
num1=10;num2=3
num1/num2
3.3333
quit


在脚本中使用bc
1.
var=`echo "options;expression" |bc `

[root@localhost110 sh]# res=`echo "scale=4;10/3" |bc`
[root@localhost110 sh]# echo $res
3.3333
2.
res=`bc<<E
options
statements
expressions
E
`
[root@localhost110 sh]# res=`bc <<E
> a=10
> b=3
> scale=4
> c=a/b
> c
> E`
[root@localhost110 sh]# echo $res
3.3333