How to get the local ip in shell-script?

0

I'm doing a script that needs the IP of the machine on the network, tried in many ways without success until I discovered 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 this?

    
asked by anonymous 07.08.2017 / 04:21

2 answers

4

Remembering that the same machine can have multiple 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'
    
07.08.2017 / 20:39
2

Another option

: ~ $ hostname -I

192.168.1.105 172.17.0.1

    
10.08.2017 / 18:53