shell指令碼之檔案測試操作符及整數比較符,

來源:互聯網
上載者:User

shell指令碼之檔案測試操作符及整數比較符,

一、檔案測試操作符:

  在書寫測試運算式是,可以使用一下的檔案測試操作符。

  

  更多的參數可以help test或者man bash

二、字串測試操作符:

  字串測試操作符的作用:比較兩個字串是否相同、字元長度是否為0,字串是否為null(註:bash區分長度字串和Null 字元串)

  “=”比較兩個字串是否相同,與“==”等價,如: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 false11 [root@CentOS /]# [ -n "$file1" -o -z "$file2" ] && echo ture || echo false 12 ture13 [root@CentOS /]# [[  "$file1" =  "$file2"  ]] && echo  true || echo false    14 true15 [root@CentOS /]# [[  "$file1" !=  "$file2"  ]] && echo  true || echo false16 false17 [root@CentOS /]# [[ -n $file1 && -n $file2  ]] && echo  true || echo false18 false19 [root@CentOS /]# [[ -n $file1 || -n $file2  ]] && echo  true || echo false  20 false21 [root@CentOS /]# [[ -n $file1 || -z $file2  ]] && echo  true || echo false22 true
View Code

    整數測試舉例:

  

  
 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 false11 [root@CentOS /]# [ $a1 -gt $a2 ] && echo true || echo false 12 false13 [root@CentOS /]# [ $a1 -lt $a2 ] && echo true || echo false 14 true15 [root@CentOS /]# [ $a1 -eq $a2 ] && echo true || echo false  16 false17 [root@CentOS /]# echo $a1 $a218 12 13
View Code

 

   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.