Bash, input validation: request for comments
Lo peeps,
I'm trying to find an way to have minimal input string validation in Bash. Declaring static_char_restr should really be done in the shells central profile, I'm not worried about performance right now (though I did set max chars) and input should be fed escaped where necessary wrt "the usual suspects". Be aware I'm also trying to minimize usage of GNU utils, like using "index" instead of grep. As far as I can see the only problem "index" has is wrt parenthesis. If you see room for improvement, I would be gratefull for your comments*. [code] function valStr() { declare -r static_char_restr="1234567890-_./@#abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" declare -r str_len="256" local str charPos charC; str=( $@ ) if [ -z "${str}" -o "${#str}" -gt "${str_len}" ]; then return 1; fi let charC=${#str}-1; for charPos in $(seq 0 "$charC"); do expr index "${str[0]:${charPos}:1}" " ${static_char_restr}" >/dev/null case "$?" in 0) ;; 1|*) return 1;; esac; done; } [code] *To put it bluntly: those with a leetness complex or compulsive urge to post "use language x" oneliners and the like are respectfully requested to move on. |
One qool feature of bash is being able to do pattern matching/replacement with regexps. This would allow you to consolidate the restrictionchars, and simply remove anything not allowed, and/or react based on what was removed, or simply because something was removed.
Code:
#!/bin/bash |
And, which a minor change, you can check for maximum length, as well:
Code:
#!/bin/bash Code:
~/shell/unspawn> ./regexp.sh fgdsag reggr egreg ere 35y 35y ---edit--- I just realized that you already have that in your script. Oh, well.. (= |
Thanks TheLinuxDuck! You showed me an excellent way to work around the index vs parenthesis gizmoidal thingoid.
Code:
-local str charPos charC; str=( $@ ) Code:
~/shell/duckie> ./regexp.sh "" ; echo $? Code:
[unsp tmp]$ . f_valStr Ok, ok, we should prolly note both examples where not optimized against this kind of abuse, and using "openssl rand 100000" instead of perl would be too much fun: Code:
~/shell/duckie> ./regexp.sh "`perl -e 'print "0" x 100000'`" ; echo $? Code:
[unsp tmp]$ . f_valStr I sincerely hope you don't see this as me slagging off your codes, I just wanted to share that... If you or anyone else got more stuff that might help improve this, BMG! |
All times are GMT -5. The time now is 12:02 PM. |