Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Shell 編程核心技能:條件測試語法全攻略

編輯:Linux 教學

一、條件測試的四種語法形式

  • test 條件表達式
  • [ 條件表達式 ] 注意:括號與內容間必須有空格
  • [[ 條件表達式 ]] (Bash 擴展,功能更強)
  • (( 數值表達式 )) 僅用於數值比較

前三種在基本功能上等價,[[ ]] 和 (( )) 提供更豐富的運算符且避免了許多陷阱。

二、數值比較運算符

標準語法 [ ]含義(( )) 語法
int1 -eq int2相等int1 == int2 或 int1 -eq int2
int1 -ne int2不等int1 != int2
int1 -lt int2小於int1 < int2
int1 -gt int2大於int1 > int2
int1 -le int2小於等於int1 <= int2
int1 -ge int2大於等於int1 >= int2

示例:

(( "2" < "3" ))   # 返回 0 (真)
[ 1 -lt 3 ]       # 返回 0 (真)

陷阱:(( )) 中 = 是賦值運算符,不能用於比較相等,需用 ==。

三、字符串測試運算符

運算符含義
-z string字符串為空(長度 0)返回真
-n string字符串非空返回真
str1 = str2 / str1 == str2字符串相等返回真
str1 != str2字符串不等返回真
str1 < str2按字典序 str1 在 str2 之前(較少用)
str1 > str2按字典序 str1 在 str2 之後(較少用)

示例:

A=str; B=str
[ $A = $B ]   # 真
B=Str
[ $A = $B ]   # 假(區分大小寫)
[ -n $B ]     # 真
[ -z $B ]     # 假

四、文件測試運算符(常用)

  • -e file:文件存在
  • -f file:普通文件
  • -d file:目錄
  • -r/-w/-x file:可讀/可寫/可執行
  • -s file:文件大小非零
  • file1 -nt file2:file1 比 file2 新
  • file1 -ot file2:file1 比 file2 舊

五、邏輯組合

  • [ expr1 -a expr2 ] 或 [[ expr1 && expr2 ]]:邏輯與
  • [ expr1 -o expr2 ] 或 [[ expr1 || expr2 ]]:邏輯或
  • [ ! expr ] 或 [[ ! expr ]]:邏輯非

推薦使用 [[ ]] 和 (( )),語法更直觀,且避免了未加引號變量導致的語法錯誤。

Copyright © Windows教程網 All Rights Reserved