歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> shell編程中變量的運算

shell編程中變量的運算

日期:2017/3/1 9:09:18   编辑:SHELL編程

shell編程中變量的運算主要包括以下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 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

浮點數運算
內建計算器 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

Copyright © Linux教程網 All Rights Reserved