天天看點

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所在的列

#!/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"