Question

#check if the name is valid
function myfunc()
{
    #check "${1}"
    #echo "valid/invalid"
}

#these should return valid
myfunc "my_number"
myfunc "my_number1"

#these should return ivalid 
myfunc "1my_number"
myfunc "1my _number"
myfunc "my number"
myfunc "my_number?"

and so on the variable name can have only letters , numbers (but not on the beginning),.. and like all the rules for java...

Is there any function that I can use ? I do not want to reinvent the wheel...

Was it helpful?

Solution

Match the variable name against a regex, like this:

myfunc() {
    if [[ "$1" =~ ^[a-z][a-zA-Z0-9_]*$ ]]
    then
        echo "$1: valid"
    else
        echo "$1: invalid"
    fi
}

OTHER TIPS

dogbane's answer is almost complete for the context of bash variables, but it has not been updated to reflect the final comment which contains a fully working validator. According to his comment on his answer, this is intended. This answer provides a function which evaluates to true for all valid names and can be used as a condition rather than returning a value that must then be compared to something. Plus, it can be used across multiple shells.

 
The function:

isValidVarName() {
    echo "$1" | grep -q '^[_[:alpha:]][_[:alpha:][:digit:]]*$' && return || return 1
}

 
Example usage in bash:

key=...
value=...

if isValidVarName "$key"; then
    eval "$key=\"$value\""
fi


# or it might simply look like this

isValidVarName "$key" && eval "$key=\"$value\""
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top