shell编程中变量的运算主要包括以下3种字符串操作
数学运算
浮点运算一.字符串操作
字符串的连接
连接字2个字符串不需要任何连接符,挨着写即可长度获取
expr length "hello"
expr length "$str" 变量名必须放在双引号里,否者语法错误
查找字符串中字符的位置
expr index "$str" CHARS
第一个是从1 开始的,查找不到返回 0 ,返回匹配到的第一个字符的位置[root@localhost110 ~]# echo $strhello word[root@localhost110 ~]# expr index "$str" h1[root@localhost110 ~]# expr index "$str" hel (只匹配h)1[root@localhost110 ~]# expr index "$str" a0 字符串截断
expr substr "$str" POS LENGTH
POS起始位置(包含),LENGTH 长度[root@localhost110 ~]# expr substr "$str" 7 4word字符串匹配
expr "$str" : REGEXP (冒号前后都得有空格)
expr mathch "$str" REGEXP
必须完整匹配才行[root@localhost110 ~]# echo $straBcD phP2016ajax[root@localhost110 ~]# expr "$str" : "([a-z]* [a-z]*)"aBcD phP二.数学运算
逻辑运算
数值运算逻辑运算
&,|,<,>,=,!=,<=,>=
数值运算
+,-,*,/,%expr expression
result=$[expression][root@localhost110 sh]# echo $num1,$num2,$num31,2,1[root@localhost110 sh]# expr $num1<$num2-bash: 2: 没有那个文件或目录操作符两边 要有空格[root@localhost110 sh]# expr $num1<$num2 1<2[root@localhost110 sh]# expr $num1 < $num21[root@localhost110 sh]# expr $num1 = $num31[root@localhost110 sh]# expr $num1 = $num20expr中用=判断是否等在[]中==
[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浮点数运算
内建计算器 bc
bc能够识别:
数字(整型和浮点型)
变量
注释 (以 #开始的行 或者/* */)
表达式
编程语句 (如条件判断 :if-then)
函数bc -q 能忽略版本信息等提示语
scale可设置精度[root@localhost110 sh]# bc -q10/33scale=410/33.3333num1=10;num2=3num1/num23.3333quit
在脚本中使用bc
1.
var=`echo "options;expression" |bc `[root@localhost110 sh]# res=`echo "scale=4;10/3" |bc`[root@localhost110 sh]# echo $res3.33332.res=`bc<<EoptionsstatementsexpressionsE` [root@localhost110 sh]# res=`bc <<E> a=10> b=3> scale=4> c=a/b> c> E`[root@localhost110 sh]# echo $res3.3333本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-11/137231.htm