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 腳本快速取得本機 IP 位址的最佳實踐

編輯:Linux 教學

經典單行指令

IP=$(ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}')
echo $IP

指令拆解

管線階段作用
ifconfig列出所有網路介面資訊
grep 'inet addr:'過濾含 IPv4 位址的行
grep -v '127.0.0.1'排除本地回環位址
cut -d: -f2以冒號分隔,取第二欄 (IP 後段)
awk '{print $1}'取第一欄,去除尾端廣播/網遮罩資訊

進階變體:只取第一張實體網卡 IP

IP=$(ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | head -n1 | cut -d: -f2 | awk '{print $1}')

或在第一個 grep 加 -m 1 參數(GNU grep 支援):

IP=$(ifconfig | grep -m 1 'inet addr:' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}')

現代替代方案

新版 Linux 發行版建議使用 ip 指令(ifconfig 屬 net-tools 套件,已停止維護):

# 取得第一張 UP 狀態非回環介面的 IPv4
ip -4 -o addr show scope global | awk '{print $4}' | cut -d/ -f1 | head -n1
Copyright © Windows教程網 All Rights Reserved