Bash input validation
Posted 01-11-2006 at 08:28 PM by unSpawn
Takes argument and stops when character outside restricted set is found.
Don't know how much slower, didn't run any timing tests with or without yet.
Should look for optimisation.
Don't know how much slower, didn't run any timing tests with or without yet.
Code:
val_str() { declare -r str_allow="1234567890-_.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ " declare -r str_len="128"; str=( "$1" ); if [ -z "${str}" -o "${#str}" -gt "${str_len}" ]; then return 1; fi charLim=$[${#str}-1]; for charPos in $(seq 0 "$charLim"); do char="${str[0]:${charPos}:1}" expr index "${char/[\(\)]/!}" "${str_allow} " >/dev/null; case "$?" in 0) ;;*) return 1;; esac; done }
Total Comments 1
Comments
-
Thank you, I've been searching for something like that!
I took a closer look and I want to make a suggestion considering expr's return value, cause I don't think it's nice sending it to /dev/null ...
Code:# variables are labeled a bit different here ... input=( "$1" ) charlimit=$[${#input}-1] for charposition in $(seq 0 "$charlimit"); do char="${input[0]:${charposition}:1}" # the second for loop takes expr's output, ret_value; # if it's 0, the loop returns 1 and we're out for ret_value in $(expr index "$char" "${str_allow}"); do if [ ${ret_value} == 0 ]; then return 1 fi done done # if the first loop returns 0, return 0; # otherwise nothing would be returned if [ "${?}" == 0 ]; then return 0 fi
Posted 12-31-1969 at 07:00 PM by unSpawn