Shell中获取当前IP地址

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 <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"
http://linux-wiki.cn/wiki/zh-hans/Shell%E4%B8%AD%E8%8E%B7%E5%8F%96%E5%BD%93%E5%89%8DIP%E5%9C%B0%E5%9D%80
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值