shell获取ip地址 .       --erikxue 薛忠权

ifconfig返回的信息中包括IP地址,但要在Shell中获取当前IP地址,则要麻烦一些



  • 获取方法

由于不同系统中ifconfig返回信息的格式有一定差别,故分开讨论:[1]

Linux:

LC_ALL=C ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' |cut -d: -f2 | awk '{ print $1}'

FreeBSD/OpenBSD:

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

Solaris:

LC_ALL=C ifconfig -a | grep inet | grep -v '127.0.0.1' |awk '{ print $2}'

三段代码的原理类似,都是先获取含有IP的行,再去掉含有127.0.0.1的行。最后获取IP所在的列


  • 样例代码

下面是一则示例的代码[2]

#!/bin/sh# Shell script scripts to read ip address# -------------------------------------------------------------------------# Copyright (c) 2005 nixCraft project # This script is licensed under GNU GPL version 2.0 or above# -------------------------------------------------------------------------# This script is part of nixCraft shell script collection (NSSC)# Visit http://bash.cyberciti.biz/ for more information.# -------------------------------------------------------------------------# Get OS nameOS=`uname`IO="" # store IPcase $OS in
   Linux) IP=`ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'`;;
   FreeBSD|OpenBSD) IP=`ifconfig  | grep -E 'inet.[0-9]' | grep -v '127.0.0.1' | awk '{ print $2}'` ;;
   SunOS) IP=`ifconfig -a | grep inet | grep -v '127.0.0.1' | awk '{ print $2} '` ;;
   *) IP="Unknown";;esacecho "$IP"


你可能感兴趣的:(IP地址,Address)