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

前端 未结 18 1715
生来不讨喜
生来不讨喜 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: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

提交回复
热议问题