在shell脚本中获取IP地址的有效方法

Eri*_*ton 11 shell scripting command-line

上下文: 在*nix系统上,可以通过以下方式获取shell脚本中机器的IP地址:

ifconfig | grep 'inet' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}'
Run Code Online (Sandbox Code Playgroud)

或者也是这样:

ifconfig | grep 'inet' | grep -v '127.0.0.1' | awk '{print $2}' | sed 's/addr://'
Run Code Online (Sandbox Code Playgroud)

问题: 是否有更简单,仍然可移植的方式来获取在shell脚本中使用的IP地址?

(我向*BSD和Solaris用户道歉,因为上面的命令可能无效 ;我无法测试)

gho*_*g74 12

你可以用一个awk命令来完成它.无需使用太多管道.

$ ifconfig | awk -F':' '/inet addr/&&!/127.0.0.1/{split($2,_," ");print _[1]}'
Run Code Online (Sandbox Code Playgroud)


cod*_*der 5

你提供直接接口,从而减少一个grep.

ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{print $1}'
Run Code Online (Sandbox Code Playgroud)