[TriLUG] bash scripting - formatting and verifying input

Kevin Hunter hunteke at earlham.edu
Thu Feb 28 10:56:22 EST 2008


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}$/ ) {
	...

I leave it to you to simplify that for your uses, but this should be
easy enough to understand:

\d matches any digit (0-9)
  {1,3} says to match the preceding 1 to 3 times
\. says to match the literal period.
^ says to anchor the match to the beginning of the line
$ says to anchor the match to the end of the line

If you're using a late enough version of BASH, I believe you've got
regexes builtin.  The syntax might be slightly different, such as \d
might become [[:digit:]].

If you're not using Perl, sed tends to be what fills the role of
regexes.

Kevin



More information about the TriLUG mailing list