Putting IP Address into bash variable. Is there a better way

前端 未结 18 1704
生来不讨喜
生来不讨喜 2020-12-07 20:09

I\'m trying to find a short and robust way to put my IP address into a bash variable and was curious if there was an easier way to do this. This is how I am currently doing

相关标签:
18条回答
  • 2020-12-07 20:53

    Not really shorter or simpler, but it works for me:

    ip=$(ip addr show eth0 | grep -o 'inet [0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+' | grep -o [0-9].*)
    
    0 讨论(0)
  • 2020-12-07 20:54

    The "eth3" is optional (useful for multiple NIC's)

    ipaddress=`ip addr show eth3 | grep 'inet ' | awk '{ print $2}' | cut -d'/' -f1`
    
    0 讨论(0)
  • 2020-12-07 20:56

    In my case I had some more interfaces in list before eth0. By this command you can get ip4 address for any interface. For that you need to change eth0 to interface that you need.

    /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{print $1}'
    
    0 讨论(0)
  • 2020-12-07 20:57

    You can get just awk to do all the parsing of ifconfig:

    ip=$(ifconfig | gawk '
        /^[a-z]/ {interface = $1}
        interface == "eth0" && match($0, /^.*inet addr:([.0-9]+)/, a) {
            print a[1]
            exit
        }
    ')
    
    0 讨论(0)
  • 2020-12-07 20:59

    ip is the right tool to use as ifconfig has been deprecated for some time now. Here's an awk/sed/grep-free command that's significantly faster than any of the others posted here!:

    ip=$(ip -f inet -o addr show eth0|cut -d\  -f 7 | cut -d/ -f 1)
    

    (yes that is an escaped space after the first -d)

    0 讨论(0)
  • 2020-12-07 20:59

    Here is the best way to get IP address of an device into an variable:

    ip=$(ip route get 8.8.8.8 | awk 'NR==1 {print $NF}')
    

    NB Update to support new Linux version. (works also with older)

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

    Why is it the best?

    1. Hostname -I some times get only the IP or as on my VPS it gets 127.0.0.2 143.127.52.130 2a00:dee0:ed3:83:245:70:fc12:d196
    2. Hostnmae -I does not work on all system.
    3. Using ifconfig may not always give the IP you like.
      a. It will fail you have multiple interface (wifi/etcernet) etc.
      b. Main IP may not be on the first found interface
    4. Searching of eth0 may fail if interface have other name as in VPS server or wifi

      ip route get 8.8.8.8

    Tries to get route and interface to Googles DNS server (does not open any session)
    Then its easy to get the ip or interface name if you like.

    This can also be used to get a ip address of an interface to a host on a multiruted net

    0 讨论(0)
提交回复
热议问题