(轉)shell腳本之文件測試操作符及整數比較符
阿新 • • 發佈:2017-11-11
clas htm 運算 數值計算 整數 ima 分享 www 表達式
shell腳本之文件測試操作符及整數比較符
原文:http://www.cnblogs.com/Steward-Xu/p/6722592.html
一、文件測試操作符:
在書寫測試表達式是,可以使用一下的文件測試操作符。
更多的參數可以help test或者man bash
二、字符串測試操作符:
字符串測試操作符的作用:比較兩個字符串是否相同、字符長度是否為0,字符串是否為null(註:bash區分長度字符串和空字符串)
“=”比較兩個字符串是否相同,與“==”等價,如:if [“$a”=“$b”],其中$a這樣的變量最好用””括起來,因為如果中間有空格等就會出錯。更好的方法是if [“${a}”=“${b}”]。
“!=”比較兩個字符串是否相同,不同則為真。
書寫表達式是可以使用以下的測試操作符號:
三、整數二元比較操作符:
其中含有:-eq、-ne、-gt、-ge、-lt、-le在[]中使用的比較符
==、!=、>、>=、<、<=在()和[[]]中使用的比較符
四:變量的數值計算:含:“^”、“!=”以及賦值運算。
實際舉例:
多條件字符串測試舉例:
1 [root@CentOS /]# [ -z "$file1" ] && echo ture || echo false 2 ture 3 [root@CentOS /]# [ -n "$file1" ] && echo ture || echo false 4 false 5 [root@CentOS /]# [ -z "$file1" -a -z "$file2" ] && echo ture || echo false 6 ture 7 [root@CentOS /]# [ -n "$file1" -a -n "$file2" ] && echo ture || echo false 8 false 9 [root@CentOS /]# [ -n "$file1" -o -n "$file2" ] && echo ture || echo false 10 false 11 [root@CentOS /]# [ -n "$file1" -o -z "$file2" ] && echo ture || echo false 12 ture 13 [root@CentOS /]# [[ "$file1" = "$file2" ]] && echo true || echo false 14 true 15 [root@CentOS /]# [[ "$file1" != "$file2" ]] && echo true || echo false 16 false 17 [root@CentOS /]# [[ -n $file1 && -n $file2 ]] && echo true || echo false 18 false 19 [root@CentOS /]# [[ -n $file1 || -n $file2 ]] && echo true || echo false 20 false 21 [root@CentOS /]# [[ -n $file1 || -z $file2 ]] && echo true || echo false 22 true
整數測試舉例:
1 [root@CentOS /]# a1=12 2 [root@CentOS /]# a2=13 3 [root@CentOS /]# [ $a1 = $a2 ] && echo true || echo false 4 false 5 [root@CentOS /]# [ $a1 != $a2 ] && echo true || echo false 6 true 7 [root@CentOS /]# [ $a1 -le $a2 ] && echo true || echo false 8 true 9 [root@CentOS /]# [ $a1 -ge $a2 ] && echo true || echo false 10 false 11 [root@CentOS /]# [ $a1 -gt $a2 ] && echo true || echo false 12 false 13 [root@CentOS /]# [ $a1 -lt $a2 ] && echo true || echo false 14 true 15 [root@CentOS /]# [ $a1 -eq $a2 ] && echo true || echo false 16 false 17 [root@CentOS /]# echo $a1 $a2 18 12 13
(轉)shell腳本之文件測試操作符及整數比較符