Which terminal command to get just IP address and nothing else?

Solution 1:

You can write a script that only return the IP like:

/sbin/ifconfig eth0 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}'

For MAC:

ifconfig | grep "inet " | grep -v 127.0.0.1 | cut -d\  -f2

Or for linux system

hostname -i | awk '{print $3}' # Ubuntu 

hostname -i # Debian

Solution 2:

This will give you all IPv4 interfaces, including the loopback 127.0.0.1:

ip -4 addr | grep -oP '(?<=inet\s)\d+(\.\d+){3}'

This will only show eth0:

ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'

And this way you can get IPv6 addresses:

ip -6 addr | grep -oP '(?<=inet6\s)[\da-f:]+'

Only eth0 IPv6:

ip -6 addr show eth0 | grep -oP '(?<=inet6\s)[\da-f:]+'

Solution 3:

Generally, it is never guaranteed that a system will only have one IP address, for example, you can have both an ethernet and wlan connections, and if you have an active VPN connection then you'll have yet another IP address.

Linux

On Linux, hostname -I will list the current IP address(es). Relying on it always returning just one IP address will most likely not work as expected under some scenarios (i.e. a VPN link is up, multiple ethernet adapters, etc), so a more reliable way would be converting the result to an array and then loop over the elements:

ips=($(hostname -I))

for ip in "${ips[@]}"
do
    echo $ip
done

Note: If hostname -I returns the IP both in IPv4 and IPv6 formats then you can use instead hostname -I | cut -f1 -d' ' to only show the IPv4 IP.

OSX

On OSX, if you know the interface, you could use:

~$ ipconfig getifaddr en0
# OUTPUT: 192.168.1.123

which will return just the IP address.

To detect dynamically the (first) active network interface on MacOS:

network_device=$(scutil --dns |awk -F'[()]' '$1~/if_index/ {print $2;exit;}')
ip=$(ipconfig getifaddr "$network_device")
echo $ip
### OUTPUT: 192.168.1.123 

Also, getting the IP address becomes non-deterministic in case both a cable and wifi connections are established, when a machine has more than one ethernet interfaces, or when VPN tunnels are up.

Getting the external IP

If you need the external IP, then you can query a text-mode service, for example curl https://ipecho.net/plain would return a plain text external IP.

A faster alternative is to query a known DNS server, e.g.:

dig @ns1-1.akamaitech.net ANY whoami.akamai.net +short

Solution 4:

hostname -I  

This command will give you the exact ip address as you want in Ubuntu.