LinuxQuestions.org
Help answer threads with 0 replies.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Blogs > unSpawn
User Name
Password

Notices


Rate this Entry

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.

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 3730 Comments 1
« 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 11:54 PM.

Main Menu
Advertisement
Advertisement
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
Twitter: @linuxquestions
Open Source Consulting | Domain Registration