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

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

提交回复
热议问题