Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to get all IP addresses

Tags:

linux

bash

shell

I am trying to write a bash script to get all IP addresses on a server. The script should work on all major distros. Here is what I have:

ifconfig | grep 'inet addr:' | awk {'print $2'}

Resulting in:

addr:10.1.2.3
addr:50.1.2.3
addr:127.0.0.1

How can I first remove the addr: prefix? Second, how I can exclude 127.0.0.1?

like image 547
Justin Avatar asked Sep 21 '12 03:09

Justin


1 Answers

ifconfig was obsoleted by ip. It also has the flag -o that write outputs easy to parse. Use ip -4 to show only IPV4 addresses. Note the simpler script, it already exclude the loopback address:

ip -o addr | awk '!/^[0-9]*: ?lo|link\/ether/ {print $2" "$4}'

Or if you don't want the networks:

ip -o addr | awk '!/^[0-9]*: ?lo|link\/ether/ {gsub("/", " "); print $2" "$4}'
like image 182
Pedro Lacerda Avatar answered Sep 21 '22 16:09

Pedro Lacerda