Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash command to check if the variable name is valid

#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...

like image 259
Lukap Avatar asked Nov 08 '12 17:11

Lukap


1 Answers

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
}
like image 184
dogbane Avatar answered Sep 28 '22 14:09

dogbane