2

I'm wondering if it's possible to dynamically read in the IP addresses of network interfaces for use in a bash script. Something like:

#!/bin/bash
MYPUBLICIP= get_eth0_address
MYPRIVATEIP= get_eth0:0_address
  • How would I go about this?
  • Is it possible to distinguish between eth0 and the virtual eth0:0?

[Background] I'm trying to write a script to apply various rules to iptables for a set of VPSs. I'm trying to avoid having to fiddle around with the individual IPs of each machine.

1

2 Answers 2

5

ip will always return all the address records for a physical interface, even if you specify a virtual one.

ifconfig let's you specify a single interface, but is a bit more annoying to parse:

ifconfig eth0:0 |awk -F':| ' '/inet addr/{print $13}'

EDIT

The ip way can be managed with more selective awk, of course:

ip -o -4 addr sh |awk '/eth0:0/{print $4}'
0
2

Something like

ip -4 -o addr show dev eth0 | sed 's/\// /g' | awk '{print $4}'

should give you the bare ip address of the relevant interface.

2
  • Interesting - I'll have a play around with that. Thanks.
    – UpTheCreek
    Apr 25, 2013 at 9:01
  • It seems it returns both IP addresses assigned to the interface whether I use eth0 or eth0:0. If the order is guaranteed though, perhaps I can just select the right one from the string.
    – UpTheCreek
    Apr 25, 2013 at 9:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .