LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Go Back   LinuxQuestions.org > Blogs > unSpawn
User Name
Password

Notices

Rate this Entry

Bash input validation

Submit "Bash input validation" to Digg Submit "Bash input validation" to del.icio.us Submit "Bash input validation" to StumbleUpon Submit "Bash input validation" to Google Submit "Bash input validation" to LinuxQuestions.org
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.

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
 }
Should look for optimisation.
Posted in Uncategorized
Views 519 Comments 1 Edit Tags Email Blog Entry
« Prev     Main     Next »
Total Comments 1

Comments

  1. Old Comment
    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
    dP

    Posted 12-31-1969 at 07:00 PM by unSpawn unSpawn is offline
 


All times are GMT -5. The time now is 02:37 PM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
RSS2  LQ Podcast
RSS2  LQ Radio
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: @linuxquestions
Open Source Consulting | Domain Registration