【发布时间】:2011-01-22 15:12:04
【问题描述】:
背景: 在 *nix 系统上,可以通过这种方式在 shell 脚本中获取机器的 IP 地址:
ifconfig | grep 'inet' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}'
或者也可以这样:
ifconfig | grep 'inet' | grep -v '127.0.0.1' | awk '{print $2}' | sed 's/addr://'
问题: 是否有更直接、仍然可移植的方法来获取 IP 地址以在 shell 脚本中使用?
(my apologies to *BSD and Solaris users as the above command may not work;我无法测试)
【问题讨论】:
-
机器有多个网卡怎么办?
-
“IP 地址”是什么意思?如今,拥有两个或多个 IP 地址非常普遍,即使在工作站上也是如此......
-
是的,我想过这个问题。但这取决于脚本需要做什么。对于我的个人需求,我通常将接口名称传递给ifconfig(即
ifconfig eth0等)。我认为这会使问题过于具体。有什么建议可以让这个问题更有意义吗?谢谢!
标签: shell command-line scripting