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

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

    man hostname recommends using the --all-ip-addresses flag (shorthand -I ), instead of -i, because -i works only if the host name can be resolved. So here it is:

    hostname  -I
    

    And if you are interested only in the primary one, cut it:

    hostname  -I | cut -f1 -d' '
    
    0 讨论(0)
  • 2020-12-07 20:48

    You can take a look at this site for alternatives.

    One way would be:

    ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'
    

    A bit smaller one, although it is not at all robust, and can return the wrong value depending on your system:

    $ /sbin/ifconfig | sed -n '2 p' | awk '{print $3}'
    

    (from http://www.htmlstaff.org/ver.php?id=22346)

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

    my short version. Useful when you have multiple interface and just want the main ip.

    host `hostname` | awk '{print $4}'
    
    0 讨论(0)
  • 2020-12-07 20:50

    I think the most reliable answer is :

    ifconfig  | grep 'inet addr:' | grep -v '127.0.0.1' | awk -F: '{print $2}' | awk '{print $1}' | head -1
    

    AND

    hostname  -I | awk -F" " '{print $1}'
    

    because when you don't use head -1 it shows all ips....

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

    I am using

    IFACE='eth0'
    IP=$(ip -4 address show $IFACE | grep 'inet' | sed 's/.*inet \([0-9\.]\+\).*/\1/')
    

    The advantage of this way is to specify the interface (variable IFACE in the example) in case you are using several interfaces on your host.

    Moreover, you could modify ip command in order to adapt this snippet at your convenience (IPv6 address, etc).

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

    I've been struggling with this too until I've found there's a simple command for that purpose

    hostname -i
    

    Is that simple!

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