[TriLUG] bash scripting - formatting and verifying input
James Olin Oden
james.oden at gmail.com
Fri Feb 29 10:06:52 EST 2008
On Thu, Feb 28, 2008 at 7:17 PM, Jeremy Portzer <jeremyp at pobox.com> wrote:
> 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}$/ ) {
> > ...
> >
>
If you were going to use perl, then use the NetAddr::IP library which
validates IP
addresses when you try to instantiate an object IIRC. Other than
that, the two stage
approach that others have mentioned is quote nice, especially if you are using
capturing the data via a regex, as you first validate the dotted
notation, and then
validate the ranges.
A single regex, BTW, is not necessarily more efficient. The more
complicated you
make a regex, means more branches the regex engine has to check, more branches
means more time. But really the time to worry about in most cases is
the time it takes
initially get the complicated regex to work, and then later to fix
once you find a corner
case that you missed when you initially did it.
Finally, bad perl comes from bad programmers. Its not the
language...trust me I have seen
bad Python....it is really possible to write bad code in any language.
Cheers...james
More information about the TriLUG
mailing list