Skip to content
Joel Shaikin edited this page Jan 12, 2017 · 2 revisions

I would not use ifconfig to get the IP, rather use this solution, since it gets the IP needed to get to internet regardless of interface.

IP=$(ip route get 8.8.8.8 | awk '{print $NF;exit}') and to get last octet:

last=$(awk -F. '{print $NF}' <<< $IP) or get the last octet directly:

last=$(ip route get 8.8.8.8 | awk -F. '{print $NF;exit}')

BASH you can use:

ip='129.66.128.72' cn="${ip##*.}" echo $cn 72 Or using sed for non BASH:

cn=echo "$ip" | sed 's/^.*\.\([^.]*\)$/\1/' echo $cn 72 Using awk

cn=echo "$ip" | awk -F '\\.' '{print $NF}'

http://stackoverflow.com/questions/25118721/isolate-the-last-octet-from-an-ip-address-and-put-it-in-a-variable

Clone this wiki locally