Linux bash script to extract IP address

前端 未结 13 2381
我在风中等你
我在风中等你 2020-12-04 15:44

I want to make big script on my Debian 7.3 ( something like translated and much more new user friendly enviroment ). I have a problem. I want to use only some of the informa

相关标签:
13条回答
  • 2020-12-04 16:11
    awk '/inet addr:/{gsub(/^.{5}/,"",$2); print $2}' file
    192.168.1.103
    
    0 讨论(0)
  • 2020-12-04 16:13

    A slight modification to one of the previous ip route ... solutions, which eliminates the need for a grep:

    ip route get 8.8.8.8 | sed -n 's|^.*src \(.*\)$|\1|gp'
    
    0 讨论(0)
  • 2020-12-04 16:14

    If the goal is to find the IP address connected in direction of internet, then this should be a good solution.


    UPDATE!!! With new version of linux you get more information on the line:

    ip route get 8.8.8.8
    8.8.8.8 via 10.36.15.1 dev ens160 src 10.36.15.150 uid 1002
        cache
    

    so to get IP you need to find the IP after src

    ip route get 8.8.8.8 | awk -F"src " 'NR==1{split($2,a," ");print a[1]}'
    10.36.15.150
    

    and if you like the interface name

    ip route get 8.8.8.8 | awk -F"dev " 'NR==1{split($2,a," ");print a[1]}'
    ens192
    

    ip route does not open any connection out, it just shows the route needed to get to 8.8.8.8. 8.8.8.8 is Google's DNS.

    If you like to store this into a variable, do:

    my_ip=$(ip route get 8.8.8.8 | awk -F"src " 'NR==1{split($2,a," ");print a[1]}')
    
    my_interface=$(ip route get 8.8.8.8 | awk -F"dev " 'NR==1{split($2,a," ");print a[1]}')
    

    Why other solution may fail:

    ifconfig eth0

    • If the interface you have has another name (eno1, wifi, venet0 etc)
    • If you have more than one interface
    • IP connecting direction is not the first in a list of more than one IF

    Hostname -I

    • May get only the 127.0.1.1
    • Does not work on all systems.
    0 讨论(0)
  • 2020-12-04 16:14
    ip -4 addr show eth0 | grep -oP "(?<=inet ).*(?=/)"
    
    0 讨论(0)
  • 2020-12-04 16:17

    If you want to get a space separated list of your IPs, you can use the hostname command with the --all-ip-addresses (short -I) flag

    hostname -I
    

    as described here: Putting IP Address into bash variable. Is there a better way?

    0 讨论(0)
  • 2020-12-04 16:18

    May be not for all cases (especially if you have several NIC's), this will help:

    hostname -I | awk '{ print $1 }'
    
    0 讨论(0)
提交回复
热议问题