PDA

View Full Version : Input Validation Shell Scripting



skip to my lou
03-01-2005, 08:48 AM
Does anyone know how to do input validation in a shell script?

e.g.

read numOne # Need to validate this is a number only
read letterOne # Need to validate that this is either A, B, C

skip to my lou
03-01-2005, 08:55 AM
read letterOne, okay that's a stupid question - figured it out,

What about number validation?

Brian_Jones
03-01-2005, 09:41 AM
read letterOne, okay that's a stupid question - figured it out,

What about number validation?

i guess this is unix shell scripting right (or are you using perl)?!
i would use regular expressions.
if no characters are [A-Z] or [0-9], etc. would be false.

skip to my lou
03-01-2005, 09:56 AM
Good morning Brian,

okay, hmm, using case + regex, [0-9] would only pick up single digit?

this what I got so far but it only picks up a single digit, and for some reason when I use something like [+-]?[0-9][0-9]? theres always a syntax error...

I thought [+-] will allow for the first char to be either + or - or nothing at all because of the ? making it optional - same with [0-9]?

hmm seems dodgy.




read numOne

case $numOne in
[0-9]) echo number;;
*) echo invalid;;
esac

Brian_Jones
03-01-2005, 10:45 AM
warn "has nondigits" if /\D/;
warn "not a natural number" unless /^\d+$/; # rejects -3
warn "not an integer" unless /^-?\d+$/; # rejects +3
warn "not an integer" unless /^[+-]?\d+$/;
warn "not a decimal number" unless /^-?\d+\.?\d*$/; # rejects .2
warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
warn "not a C float"
unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;

ps. langer is out in the cricket

skip to my lou
03-01-2005, 10:58 AM
warn "has nondigits" if /\D/;
warn "not a natural number" unless /^\d+$/; # rejects -3
warn "not an integer" unless /^-?\d+$/; # rejects +3
warn "not an integer" unless /^[+-]?\d+$/;
warn "not a decimal number" unless /^-?\d+\.?\d*$/; # rejects .2
warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
warn "not a C float"
unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;

ps. langer is out in the cricket

Wow, did you write that on your own? :D

skip to my lou
03-01-2005, 11:18 AM
How do I match up that regex against a variable (in bash script); case doesn't seem to accept the advanced regex

skip to my lou
04-01-2005, 04:31 PM
I got this working thanks to Barry. Used tmpChar=${numOne:$tmpCounter:1}, while loop and ${#numOne} And then can match using regex as Brian suggested. Thanks Barry and Brian!