How to get ip address of a server on Centos 7 in bash

user2650277 picture user2650277 · Jan 14, 2015 · Viewed 228.6k times · Source

Previously I used the following command in bash to find the main ip of my server

ipaddr=$(/sbin/ifconfig|grep inet|head -1|sed 's/\:/ /'|awk '{print $3}' | grep -v '127.0.0.1')

But in centos7 it no longer works since ifconfig isn't available and the command no longer works even if I install ifconfig using yum install net-tools

What is the equivalent command for centos 7

Thanks a lot

Answer

Alexander picture Alexander · Jan 14, 2015

You can use hostname command :

ipaddr=$(hostname -I)

-i, --ip-address: Display the IP address(es) of the host. Note that this works only if the host name can be resolved.

-I, --all-ip-addresses: Display all network addresses of the host. This option enumerates all configured addresses on all network interfaces. The loopback interface and IPv6 link-local addresses are omitted. Contrary to option -i, this option does not depend on name resolution. Do not make any assumptions about the order of the output.