Bash編程中的字符串比較實用一般編程語言的比較操作符:
Bash中數值比較的操作符:
比較 | 描述 | 比較 | 描述 |
n1 -eq n2 | n1等於n2 | n1 -ne n2 | n1不等於n2 |
n1 -gt n2 | n1大於n2 | n1 -lt n2 | n1小於n2 |
n1 -ge n2 | n1大於等於n2 | n1 -le n2 | n1小於等於n2 |
數值比較只支持整數,不支持浮點數。
Bash中字符串比較的操作符:
比較 | 描述 | 比較 | 描述 |
str1 = str2 | str1 等於 str2 | str1 > str2 | str1 大於 str2 |
str1 != str2 | str1 不等於 str2 | -z str | str的長度爲零,即爲空 |
str1 < str2 | str1 小於 str2 | -n str | str的長度不爲零,即不爲空 |
在用'>'和'<'進行字符串比較時,要對'>'和'<'作轉義,否則會被shell解釋爲輸出和輸入重定向符。
例:
#!/bin/bash
str="abcdefg"
file=./datafile
if [ "$str" > $file ]; then
stat $file
fi
以上腳本代碼的實質是在當前目錄創建了一個文件名爲'datafile'的空文件!並且無關str的內容!
進行字符串比較時,對變量引用實用雙引號引起來,否則容易出問題。
示例:
#!/bin/bash
str1="hello, 51cto"
str2="happy new year"
if [ "$str1" \> "$str2" ]; then
echo "str1 is larger than str2"
else
echo "str1 is smaller than str2"
fi
Bash中文件比較的操作符:
比較 | 描述 | 比較 | 描述 |
-e file | file文件是否存在 | -s file | file存在且不爲空 |
-d file | file存在且是目錄 | -O file | file存在且被當前用戶擁有 |
-f file | file存在且爲文件 | -G file | file存在且默認組是當前用戶組 |
-r file | file存在且具有可讀權限 | file1 -nt file2 | file1比file2新 |
-w file | file存在且具有可寫權限 | file1 -ot file2 | file1比file2舊 |
-x file | file存在且具有可執行權限 |
對文件進行 -r -w -x 相關的權限判斷時,是相對當前執行該腳本或該操作的用戶而言的。比如,
-rwxr--r-- redhat redhat testfile ,若以redhat用戶執行" [ -x testfile ]",則結果爲真,否則,其它任何普通用戶執行,結果爲假。
若判斷的文件是符號鏈接文件,則對文件進行 -r -w -x 相關的權限判斷,以當前鏈接文件鏈接到的那個真正的文件或目錄的權限來作判斷。另外,如果只是刪除符號鏈接文件本身,而不是要刪除符號鏈接文件鏈接的那個文件或目錄,使用命令:unlink symbolic_file_name
(())命令 和 [[]]命令
雙圓括號命令允許在比較中包含高級數學賦值表達式或數學比較表達式。除了支持test命令的基本數學操作符,還支持以下數學操作符:
符號 | 描述 | 符號 | 描述 |
val++ | 先引用後自加一 | << n | 左移n位 |
val-- | 先引用後自減一 | >> n | 右移n位 |
++val | 先自加一後引用 | && | 邏輯與 |
--val | 先自減一後引用 | || | 邏輯或 |
! | 邏輯取反 | & | 按位與 |
~ | 按位取反 | | | 按位或 |
** | 冪運算 | ||
在雙圓括號內的表達式,'>','<'不用作轉義。表達式也可以不用和前後雙圓括號之間有空格。
在雙圓括號內的表達式中,對變量的引用可以不用加'$',而直接使用變量名
#!/bin/bash
var1=10
if ((var2=var1**2)) && ((var2 > 50)) ; then
echo "the value of var2 is more than 50."
fi
echo "var2=$var2"
雙方括號命令對test命令的擴展,體現在雙方括號內的字符串表達式支持glob的正則表達式
#!/bin/bash
match_str="9 .99"
if [[ $match_str = 9?.* ]]; then
echo "match by glob -> match_str :$match_str "
fi
本文出自 “被褐懷玉徳善人間” 博客,請務必保留此出處http://deshan.blog.51cto.com/9295575/1542707