I\'m trying to use just the IP address (inet) as a parameter in a script I wrote.
Is there an easy way in a unix terminal to get just the IP address, rather than loo
hostname -I
This command will give you the exact ip address as you want in Ubuntu.
You can also use the following command:
ip route | grep src
NOTE: This will only work if you have connectivity to the internet.
I always wind up needing this at the most unexpected times and, without fail, wind up searching for threads like this on SO. So I wrote a simple script to get IPv4 addresses via netstat, called echoip
- you can find it here. The bash for network addresses looks like this, it also gets your public address from ipecho.net:
IPV4='\d+(\.\d+){3}'
INTERFACES=`netstat -i | grep -E "$IPV4" | cut -d ' ' -f 1`
INTERFACE_IPS=`netstat -i | grep -oE "$IPV4"`
for i in "${!INTERFACES[@]}"; do
printf "%s:\t%s\n" "${INTERFACES[$i]}" "${INTERFACE_IPS[$i]}"
done
The echoip
script yields an output like this:
$ echoip
public: 26.106.59.169
en0: 10.1.10.2
#!/bin/sh
# Tested on Ubuntu 18.04 and Alpine Linux
# List IPS of following network interfaces:
# virtual host interfaces
# PCI interfaces
# USB interfaces
# ACPI interfaces
# ETH interfaces
for NETWORK_INTERFACE in $(ls /sys/class/net -al | grep -iE "(/eth[0-9]+$|vif|pci|acpi|usb)" | sed -E "s@.* ([^ ]*) ->.*@\1@"); do
IPV4_ADDRESSES=$(ifconfig $NETWORK_INTERFACE | grep -iE '(inet addr[: ]+|inet[: ]+)' | sed -E "s@\s*(inet addr[: ]+|inet[: ]+)([^ ]*) .*@\2@")
IPV6_ADDRESSES=$(ifconfig $NETWORK_INTERFACE | grep -iE '(inet6 addr[: ]+|inet6[: ]+)' | sed -E "s@\s*(inet6 addr[: ]+|inet6[: ]+)([^ ]*) .*@\2@")
if [ -n "$IPV4_ADDRESSES" ] || [ -n "$IPV6_ADDRESSES" ]; then
echo "NETWORK INTERFACE=$NETWORK_INTERFACE"
for IPV4_ADDRESS in $IPV4_ADDRESSES; do
echo "IPV4=$IPV4_ADDRESS"
done
for IPV6_ADDRESS in $IPV6_ADDRESSES; do
echo "IPV6=$IPV6_ADDRESS"
done
fi
done
I would Use Hostname -L
to get just the IP to use as a variable in a script.