[TriLUG] bash scripting - formatting and verifying input

Jeremy Portzer jeremyp at pobox.com
Thu Feb 28 19:17:23 EST 2008


Kevin Hunter wrote:
> At 10:09a -0500 on Thu, 28 Feb 2008, Roy Vestal wrote:
>> I know it's simple, but this is going to be a somewhat automated
>> system that needs to verify the ip address. I was thinking sed but it
>> seems a little complicated. I just need to verify it's in the
>> xxx.xxx.xxx.xxx format, not any specific numbers in the octets.
> 
> If you don't need to verify that it's in any specific octets, then
> think regular expressions.  However, from bitter and lovely experience,
> I've found that being pedantic about testing input is a Very Good
> Thing.  By taking another 3 minutes to specifically check your octets
> now, you potentially will save some poor schmo an hour+ in a years
> time.  And who knows?  That poor schmo might be you!
> 
> However, to answer your question with the caveat that verification
> is not necessary, in Perl-speak, a regex that would work:
> 
> if ( $IPADDR =~ m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ ) {
> 	...
> 

Here's a question/challenge - how would you modify this to verify that 
each octet is between zero and 255?

You can't just make sure that the first digit is a 1 or 2, because that 
would prevent ".95" from matching.

My approach would probably be to use Perl's "split" function to separate 
the octets into individual variables, and then check each one with 
integer comparisons.  But I'd be interested to know if there's a way to 
do it within a regexp.

--Jeremy



More information about the TriLUG mailing list