How to get the local ip in shell-script?

Asked

Viewed 2,285 times

0

I’m making a script that needs the machine IP on the network, tried several ways unsuccessfully until I figured out a way:

ip="`ip addr show | grep global | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' | sed -n '1p'`"

echo $ip

It worked, but it seems to me a very dirty method. Is there any other way to do it?

3 answers

4


Remembering that the same machine may have several addresses of IP. The solutions proposed here apply to machines Linux and return only the address of IP primary:

1) Using hostname + cut:

$ hostname -I | cut -f1 -d' '

2) Using hostname + awk:

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

3) Using ifconfig + grep:

$ ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'
  • I would take it with ifconfig, but Debian 9 no longer comes with ifconfig by default and I didn’t know that hostname showed IP, thank you very much. !

  • @Everton: Have you looked at /sbin/ifconfig ?

  • The net-tools package, (which includes Arp, ifconfig, iptunnel, netstat, route, iwconfig, and nameif) was marked as obsolete by the linux foundation and therefore no longer used. https://wiki.linuxfoundation.org/networking/net-tools

  • In Debian 9 the good old ifconfig has become obsolete, now the command is used ip -stats -color -human addr

2

Other option

:~$ hostname -I

192.168.1.105 172.17.0.1

0

Shows all Ips:

ip addr show | grep global | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])'

Shows the main IP address:

ip addr show | grep global | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' | sed -n '1p'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.