[Gllug] Re: Bash Data validation libraries
ccooke
ccooke-gllug at gkhs.net
Tue Feb 14 20:40:22 UTC 2006
On Tue, Feb 14, 2006 at 04:04:27PM +0000, Richard wrote:
> Richard Jones wrote:
>
> >A lot of these things can be done fairly simply using the available
> >tools. For instance, a naive check of IP addresses might be:
> >
> >
> <snip>
>
> >^[1-9][0-9]?[0-9]?\.[1-9][0-9]?[0-9]?\.[1-9][0-9]?[0-9]?\.[1-9]\[0-9]?[0-9]?$ ]]; then
> >
> >
> <snip>
> At the risk of sounding rude, what about the less naive version?
>
This is a fairly verbose and accurate checker:
--------- 8< ---------
#!/bin/bash
# Turn on extended globbing
shopt -s extglob
function isip
{
local ip="$1"
local octets=0
local octet
# Check the basic structure ( number.number.number.number )
if [[ ${ip}. == +(+([0-9]).) ]]
then
# now we know it's safe, check the numbers:
for octet in ${ip//./ }
do
if (( ++octets > 4 ))
then
echo "Invalid IP! Too many octets"
return 1
elif (( $octet > 255 ))
then
echo "Invalid IP! Octet $octets is out of range"
return 1
fi
done
else
echo "Invalid IP! Not in dotted-octet notation"
return 1
fi
# if we got here, it's a valid IP. The return below is just to
# say this explicitly.
return 0
}
isip 10.1.10.30 && echo 'ok'
isip 10.1.1000.1 && echo 'not ok'
isip not.even.trying && echo 'you must be joking'
--------- >8 ---------
This is full of modern shellisms, so don't try to run it anywhere without a
version of ksh93 or bash version 2 (which will be almost any bash you'll
ever encounter by now).
For ksh93, you can skip the 'shopt -s extglob' - extended globbing is always
turned on there.
--
for((P=10**8,Q=P/100,X=320*Q/(`tput cols`-1),Y=210*Q/`tput lines`,y=-105*Q,v=-2\
20*Q,x=v;y<105*Q;x=v,y+=Y));do for((;x<P;a=b=i=k=c=0,x+=X));do for((;a*a+b*b<2*\
P*P&&i++<99;a=((c=a)*a-b*b)/P+x,b=2*c*b/P+y));do :;done;(((j=(i<99?i%16:0)+30)>\
37?k=1,j-=8:0));echo -ne "\E[$k;$j"mE;done;echo -e \\E[0m;done # Charles Cooke
--
Gllug mailing list - Gllug at gllug.org.uk
http://lists.gllug.org.uk/mailman/listinfo/gllug
More information about the GLLUG
mailing list