Shell 中驗證 IPv4 地址有多種正則寫法,本文對比 grep、awk、cut、純 Bash 參數擴展四種路徑,並給出生產環境推薦的最佳實踐。
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 ]]
}
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}
'
}
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
}
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 -E | grep | 中 | 高 | 腳本開頭快速驗證 |
| awk | awk | 中 | 中 | 大量 IP 管線過濾 |
| cut 迴圈 | cut | 慢 | 低 | 極舊系統 (bash 3-) |
| 純 Bash | 無 | 最快 | 高 | 現代 Linux (bash 4+) |
ip -4 -o addr show | awk '{print $4}' | cut -d/ -f1
# 或
ifconfig | awk '/inet /{print $2}' | cut -d: -f2