0

I'm maintaining a bash script that runs on RHEL 5. Given an domain name, I want to ensure that there is an interface on the current machine listening to the expected IP address.

# Check that the IP is bound to this host, to avoid running on the wrong machine.
IP=$(dig +short ${EXPECTED_SUBDOMAIN}.example.com | tail -n 1)

if ! $(/sbin/ifconfig 2>/dev/null | /bin/grep -q $IP) ; then
    echo "IP for ${EXPECTED_SUBDOMAIN} ($IP) doesn't appear to be on this host"
    exit 1
fi

This breaks when IP addresses are substrings of each other. If my expected IP address is 1.2.3.4, it doesn't exit if the machine has an IP address (or even subnet mask!) of 11.2.3.4 or 1.2.3.40.

The only solution I can see is grep "inet addr:${IP} " but it seems dirty to search for other text.

Is there are more robust way to find out the IP addresses of interfaces (without getting confused by things like subnet masks) and compare them? Is there a better approach?

Wilfred Hughes
  • 29,846
  • 15
  • 139
  • 192
  • 1
    id say its fine to use the extra text in your grep pattern to ensure you only match in the area you want from the string. – dethorpe Jun 26 '14 at 14:06

2 Answers2

1

use word boundary in your grep:

if ! $(/sbin/ifconfig 2>/dev/null | /bin/grep -qE "\<$IP\>" ; then
...
lihao
  • 583
  • 3
  • 6
  • This answer was auto-flagged as low quality. If you explained how "word boundary" work it would make for a better and more informative answer. – Sled Jun 26 '14 at 15:11
0

Try this:

 /sbin/ip addr | grep -Po 'inet \K.*?(?=(/| ))'| /bin/grep -q "^$IP$"

Matching the beginning and end of string should solve your problem if the input is also filtered.

PS. I find ip addr better than ifconfig for vitual ips.

Tiago Lopo
  • 7,619
  • 1
  • 30
  • 51