regular expression help

Hi, I have a small script which uses egrep and a set of regexes to validate an IP address, however, i want to make it so that if somebody puts a leading space in front of the IP address to be validated it will fail, so this is my script

#!/bin/bash

#function
ip_checker() {

result=$( echo $1 | egrep "(^[01]?[0-9][0-9]?|2[0-4][0-9]|25[0-4])\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-4])\.([01]?[0-9][0-9]?|2[0-4]
[0-9]|25[0-4])\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-4]$)" )

if [ -z $result ]; then
echo " "
echo "That IP is invalid"
exit 1
else
echo "IP looks fine"
fi
}


IP=" 192.168.1.2"
ip_checker $IP

notice the space before the IP that I have set in $IP variable (in bold above)

this returns

# ./test.sh
IP looks fine

its the same however many spaces i put in front of the IP, however, if i put a different character in front of the IP e.g

IP="x192.168.1.2"
ip_checker $IP

it fails as expected

# ./test.sh
That IP is invalid

its just those pesky spaces .. as you can see I have entered a ^ in the regex at the beginning but that seems to be ignored

is there something im doing wrong here ?

No, it's not ignored. In fact, any spaces you put before the IP address are stripped away with the echo in

result=$( echo $1 | egrep "(^[01]?[0-9][0-9]?|2[0-4][0-9]|25[0-4])\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-4])\.([01]?[0-9][0-9]?|2[0-4]
[0-9]|25[0-4])\.([01]?[0-9][0-9]?|2[0-4][0-9]|25[0-4]$)" )

, most probably even sooner, with the call to ip_checker
Put double quotes around the $1/$IP and your script will fail as expected.

Just as a side node: most UNIX shells (all that I know) use spaces as argument seperators and strip away any that aren't explicitly literal (using quotes). There's usually no need to check for them manually.

Also try changing

to

... egrep "^([01] ...

to have the space in the beginning recognized as not allowed.


  1. 01 ↩︎

if you are able to use Perl and install module Data::Validate::IP, it makes your life much easier

#!/usr/bin/perl

use Data::Validate::IP qw(is_ipv4);
$ip = "192.168.0.1";
if(is_ipv4($ip)){
        print "$ip is valid ip address\n";
}else{
        print "$ip is an ip address\n";
}
$ip = "1.1.257.2";
if(is_ipv4($ip)){
        print "$ip is valid ip address\n";
}else{
        print "$ip is Not an ip address\n";
}


output

# ./test.pl
192.168.0.1 is valid ip address
1.1.257.2 is Not an ip address

thats great thanks guys