Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Linux Shell if 條件判斷完整語法與實戰範例

編輯:Linux 系統常見問題解答

Shell 腳本中的 if 語句是流程控制核心。本文系統整理字串比較、數值比較、檔案測試、複合邏輯四大判斷類型語法,並提供豐富實戰範例與常見錯誤避坑指南。

一、字串判斷運算子

運算子為真條件
str1 = str2內容、長度完全相同
str1 != str2不相等
-n str1長度 > 0 (非空)
-z str1長度 = 0 (空字串)
str1非空 (等同 -n)

二、數值判斷運算子

運算子為真條件
int1 -eq int2相等
int1 -ne int2不等
int1 -gt int2大於
int1 -ge int2大於等於
int1 -lt int2小於
int1 -le int2小於等於

三、檔案測試運算子

運算子為真條件
-r file可讀
-w file可寫
-x file可執行
-f file一般檔案
-d file目錄
-c file字元特殊裝置
-b file區塊特殊裝置
-s file檔案大小非 0
-t fd檔案描述符指向終端機 (預設 fd=1)

四、複合邏輯運算子

運算子意義
-a邏輯 AND (且)
-o邏輯 OR (或)
!邏輯 NOT (非)

五、實戰範例集

範例 1:目錄/檔案存在性檢查與自動建立

#!/bin/sh
myPath="/var/log/httpd/"
myFile="/var/log/httpd/access.log"

# 檢查目錄是否存在且可執行 (可進入)
if [ ! -x "$myPath" ]; then
    mkdir -p "$myPath"
fi

# 檢查目錄是否存在 (較通用)
if [ ! -d "$myPath" ]; then
    mkdir -p "$myPath"
fi

# 檢查檔案是否存在
if [ ! -f "$myFile" ]; then
    touch "$myFile"
fi

# 檢查變數是否有值
if [ ! -n "$myVar" ]; then
    echo "$myVar is empty"
    exit 0
fi

範例 2:兩個變數相等比較

if [ "$var1" == "$var2" ]; then
    echo '$var1 eq $var2'
else
    echo '$var1 not eq $var2'
fi

範例 3:多條件分支 (elif)

#!/bin/sh
SYSTEM=$(uname -s)

if [ "$SYSTEM" = "Linux" ]; then
    echo "Linux"
elif [ "$SYSTEM" = "FreeBSD" ]; then
    echo "FreeBSD"
elif [ "$SYSTEM" = "Solaris" ]; then
    echo "Solaris"
else
    echo "Unknown: $SYSTEM"
fi

六、關鍵語法陷阱 (必讀)

1. if 與 [ 之間 必須有空格
2. [ 與判斷條件之間 必須有空格
3. 判斷條件與 ] 之間 必須有空格
4. ] 與 ; (或 then) 之間 不能有空格

錯誤寫法:if [$a=1];then
正確寫法:if [ $a = 1 ]; then

七、進階技巧:雙括號與雙中括號

  • (( ... )):算術評估,支援 > < == && || 等 C 風格運算子
  • [[ ... ]]:增強測試,支援模式比對 == =~ (正則)、字串比較無需加引號、邏輯運算子 && ||

建議:新腳本優先使用 [[ ... ]] 與 (( ... )),相容性更好、錯誤更少。

Copyright © Windows教程網 All Rights Reserved