当前位置: > shell编程 >

Shell中获取IP地址

时间:2014-07-11 00:50来源:linux.it.net.cn 作者:IT网

linux下:

 

ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'
先获取含有IP的行,再去掉含有127.0.0.1的行。最后获取IP所在的列

 

 

#!/bin/sh
# shell script scripts to read ip address
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project <http://cyberciti.biz/fb/>
# 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 name
OS=`uname`
IO="" # store IP
case $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";;
esac
echo "$IP"


vi ip.sh

#!/bin/bash
ifconfig $1|sed -n 2p|awk  '{ print $2 }'|awk -F : '{ print $2 }'

##ifconfig $1|sed -n 2p|awk  '{ print $2 }'|tr -d 'addr:'#这个也可以实现####

执行:

./ip.sh eth0
192.168.2.4
(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容