如何从Mac上的ifconfig获取格式为“Interface:IP Address”的输出

时间:2011-08-24 20:40:56

标签: regex grep macos ifconfig

我正在尝试从ifconfig中获取以下格式化输出:

en0: 10.52.30.105
en1: 10.52.164.63

我已经能够通过以下命令至少弄清楚如何获取IP地址(除去localhost),但这还不足以满足我的要求:

ifconfig  | grep -E 'inet.[0-9]' | grep -v '127.0.0.1' | awk '{ print $2}'

谢谢!

2 个答案:

答案 0 :(得分:7)

这适用于FreeBSD,它是苹果的核心: - )

#!/bin/sh
for i in $(ifconfig -l); do
   case $i in
   (lo0)
      ;;
   (*)
      set -- $(ifconfig $i | grep "inet [1-9]")
      if test $# -gt 1; then
         echo $i: $2
      fi
   esac
done

答案 1 :(得分:0)

在Debian / RHEL系统上,您可以执行以下操作---

#!/bin/sh
echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"

echo "Interface: IP : MASK : BROADCAST : HWADDR"

echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"

for i in $(ifconfig -a| grep -v ^$| grep ^[a-z*] | awk '{print $1}')

do

     case $i in 

           (lo)
                   ;;

           (*)
         ip=`(/sbin/ifconfig $i | awk /'inet addr/ {print $2}' | cut -f2 -d":" )`
         bcast=`(/sbin/ifconfig $i | awk /'Bcast/ {print $3}' | cut -f2 -d":" )`
         mask=`(/sbin/ifconfig $i | awk /'inet addr/ {print $4}' | cut -f2 -d":" )`
         hwaddr=`(/sbin/ifconfig $i | awk /'HWaddr/ {print $4,$5}' | cut -f2 -d" " )`

         if [ -z $ip ]; then
            ip="NA"
         fi

         if [ -z $bcast ]; then
           bcast="NA"
         fi

         if [ -z $mask ]; then
           mask="NA"
         fi

         if [ -z $hwaddr ]; then
           hwaddr="NA"
         fi

            echo $i: $ip : $mask : $bcast : $hwaddr
            ;;

    esac
done