萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Shell 正則表達式驗證 IPv4 地址多種寫法

Shell 中驗證 IPv4 地址有多種正則寫法,本文對比 grep、awk、cut、純 Bash 參數擴展四種路徑,並給出生產環境推薦的最佳實踐。

方法一:grep 擴展正則 (最直觀)

validate_ip_grep() {
    local ip=$1
    # 0-255 精確正則
    local octet='(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])'
    local regex="^${octet}\\.${octet}\\.${octet}\\.${octet}$"
    [[ $ip =~ $regex ]]
}

方法二:awk 逐欄位檢查 (適合管線)

validate_ip_awk() {
    echo "$1" | awk -F. '
        NF==4 && $1>=0 && $1<=255 && $2>=0 && $2<=255 && $3>=0 && $3<=255 && $4>=0 && $4<=255 {exit 0}
        {exit 1}
    '
}

方法三:cut + 迴圈 (相容舊 Shell)

validate_ip_cut() {
    local ip=$1 tmp=/tmp/ipcheck.$$
    echo "$ip" > "$tmp"
    echo "$ip" | grep -Eq '^[0-9]{1,3}(\.[0-9]{1,3}){3}$' || { rm -f "$tmp"; return 1; }
    for f in 1 2 3 4; do
        local octet=$(cut -d. -f$f "$tmp")
        [ "$octet" -ge 0 ] && [ "$octet" -le 255 ] || { rm -f "$tmp"; return 2; }
    done
    rm -f "$tmp"
    return 0
}

方法四:純 Bash 參數擴展 (效能最佳、無外部程序)

validate_ip_bash() {
    local ip=$1
    [[ $ip =~ ^[0-9]{1,3}(\.[0-9]{1,3}){3}$ ]] || return 1
    local IFS=.
    set -- $ip
    for octet; do
        (( octet >= 0 && octet <= 255 )) || return 2
    done
    return 0
}

效能與相容性對比

方法相依工具速度可讀性推薦場景
grep -Egrep中高腳本開頭快速驗證
awkawk中中大量 IP 管線過濾
cut 迴圈cut慢低極舊系統 (bash 3-)
純 Bash無最快高現代 Linux (bash 4+)

取得本機所有 IPv4

ip -4 -o addr show | awk '{print $4}' | cut -d/ -f1
# 或
ifconfig | awk '/inet /{print $2}' | cut -d: -f2
copyright © 萬盛學電腦網 all rights reserved