Shell获取当前主机ip地址:
1.方法一
使用ifconfig 并指定接口:
ifconfig eth0|grep "inet addr:"|awk -F":" '{print $2}'|awk '{print $1}'
2.方法二
使用ip addr命令
ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | cut -f1 -d '/'
grep -A2 显示匹配后的后2行
或者:
ip addr | grep 'state UP' -A2 | tail -n1 | awk '{print $2}' | awk -F"/" '{print $1}'
#!/bin/sh
os_ver=`uname`
if [ "$os_ver" = "AIX" ]; then
n=`ifconfig -a |grep -i up|grep -v inet6 |awk -F":" '{print $1}'|wc -l`
i=0
echo [
for ethname in `ifconfig -a |grep -i up|grep -v inet6 |awk -F":" '{print $1}'`
do
i=`expr $i + 1`
ipaddr=`ifconfig $ethname|grep "inet"|grep -v "inet6"|awk '{print $2}'`
if [ $i -lt $n ]; then
echo \{\"name\":\"${ethname}\",\"ip\":\"${ipaddr}\"\},
else
echo \{\"name\":\"${ethname}\",\"ip\":\"${ipaddr}\"\}
fi
done
echo ]
else
n=`ifconfig | grep "Link" | grep -v inet6 | awk '{print $1}'|wc -l`
i=0
echo [
for ethname in $(ifconfig | grep "Link" | grep -v inet6 | awk '{print $1}')
do
i=`expr $i + 1`
ipaddr=`ifconfig $ethname|grep "inet addr:"|awk -F":" '{print $2}'|awk '{print $1}'`
if [ $i -lt $n ]; then
echo \{\"name\":\"${ethname}\",\"ip\":\"${ipaddr}\"\},
else
echo \{\"name\":\"${ethname}\",\"ip\":\"${ipaddr}\"\}
fi
done
echo ]
fi