shell的比較和判斷

來源:互聯網
上載者:User

標籤:des   style   color   io   使用   ar   檔案   sp   on   

比較和判斷是程式流程式控制制的要素,此文總結一下shell的比較和判斷語句,方便尋找使用。

1. 重要的比較操作符

    大於: -gt

    小於: -lt    

    大於或等於: -ge

    小於或等於: -le

    等於: -eq

    不等於: -ne

   

舉例:

    if [ $var -eq 0]  # 如果$var等於0時

    if [ $var -ne 0 -a $var -gt 2 ] #邏輯與 -a

    if [ $var -ne 0 -o $var -gt 2 ] #邏輯或 -o

 

2. 檔案相關的判斷測試

    [ -f $file_var ] : 如果$file_var是存在的檔案路徑或檔案名稱,則返回真;

    [ -x $var ] : 如果$var具有檔案可執行許可權,則返回真;

    [ -d $var ] : 如果$var是目錄,則返回真;

    [ -e $var ] : 如果$var是存在的檔案,則返回真;

    [ -c $var ] : 如果$var是存在的字元裝置檔案,則返回真;

 

附上英文:

-a file exists. 
-b file exists and is a block special file. 
-c file exists and is a character special file. 
-d file exists and is a directory. 
-e file exists (just the same as -a). 
-f file exists and is a regular file. 
-g file exists and has its setgid(2) bit set. 
-G file exists and has the same group ID as this process. 
-k file exists and has its sticky bit set. 
-L file exists and is a symbolic link. 
-n string length is not zero. 
-o Named option is set on. 
-O file exists and is owned by the user ID of this process. 
-p file exists and is a first in, first out (FIFO) special file or named pipe. 
-r file exists and is readable by the current process. 
-s file exists and has a size greater than zero. 
-S file exists and is a socket. 
-t file descriptor number fildes is open and associated with a terminal device. 
-u file exists and has its setuid(2) bit set. 
-w file exists and is writable by the current process. 
-x file exists and is executable by the current process. 
-z string length is zero. 

舉例:

fpath="etc/passwd"

if [ -e $fpath ]; then

echo "file exists";

else

echo "not exist";

fi

 

3. 字串比較

[[ $str1 = $str2 ]] : 當str1等於str2時,返回真;

[[ $str1 == $str2 ]] : 這是判斷字串是否相等的另一種寫法;

[[ $str1 != $str2 ]] : 當str1不等於str2時,返回真;

[[ $str1 > $str2 ]] : 當str1大於str2時,返回真;

[[ $str1 < $str2 ]] : 當str1小於str2時,返回真;

[[ -z $str1 ]] : 當str1包含的是Null 字元串,返回真;

[[ -n $str1 ]] : 當str1包含的是非Null 字元串,返回真;

 

shell的比較和判斷

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.