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
Few answers appear to be using the newer ip
command (replacement for ifconfig
) so here is one that uses ip addr
, grep
, and awk
to simply print the IPv4 address associated with the wlan0
interface:
ip addr show wlan0|grep inet|grep -v inet6|awk '{print $2}'|awk '{split($0,a,"/"); print a[1]}'
While not the most compact or fancy solution, it is (arguably) easy to understand (see explanation below) and modify for other purposes, such as getting the last 3 octets of the MAC address like this:
ip addr show wlan0|grep link/ether|awk '{print $2}'|awk '{split($0,mac,":"); print mac[4] mac[5] mac[6]}'
Explanation: ip addr show wlan0
outputs information associated with the network interface named wlan0
, which should be similar to this:
4: wlan0: mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether dc:a6:32:04:06:ab brd ff:ff:ff:ff:ff:ff
inet 172.18.18.1/24 brd 172.18.18.255 scope global noprefixroute wlan0
valid_lft forever preferred_lft forever
inet6 fe80::d340:5e4b:78e0:90f/64 scope link
valid_lft forever preferred_lft forever
Next grep inet
filters out the lines that don't contain "inet" (IPv4 and IPv6 configuration) and grep -v inet6
filters out the remaining lines that do contain "inet6", which should result in a single line like this one:
inet 172.18.18.1/24 brd 172.18.18.255 scope global noprefixroute wlan0
Finally, the first awk
extract the "172.18.18.1/24" field and the second removes the network mask shorthand, leaving just the IPv4 address.
Also, I think it's worth mentioning that if you are scripting then there are often many richer and/or more robust tools for obtaining this information, which you might want to use instead. For example, if using Node.js there is ipaddr-linux, if using Ruby there is linux-ip-parser, etc.
See also https://unix.stackexchange.com/questions/119269/how-to-get-ip-address-using-shell-script