简体   繁体   中英

How to find out your IP addresses using bash

I have a server that has several ip addresses. I want to work out their exact values in bash. I am looking for something like:

a=returnIpAddressStartingWith 10.60.12
b=returnIpAddressStartingWith 10.60.13

so that the following returns:

> echo $a
10.60.12.23

Is there a reasonable way of doing this on linux?

You can use a function like this for searching:

findip() {
   ip -4 addr | awk -v ip="$1" -F '[/[:blank:]]+' '$2 == "inet" && index($3, ip){print $3}'
}

And find the IP by:

a=$(findip '10.60.12')

Parse it out of the 'ip addr show' list using grep/awk/cut, then optionally, if you need to access it as an array, copy your list into a Bash array:

# Create a string that is the list of all variables
IPSTR=`ip addr show | fgrep 'inet ' | fgrep -v '127.0.0.1' | awk '{ print $2 }' | cut -d '/' -f 1`
I=0
for IP in $IPSTR ; do
    IPARY[$I]=$IP
    I=$(($I+1))
done
echo "First IP in array is ${IPARY[0]}"
echo "Number of IP addresses in array is ${#IPARY[*]}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM