JavaScript
x
#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…
Advertisement
Answer
Match the variable name against a regex, like this:
JavaScript
myfunc() {
if [[ "$1" =~ ^[a-z][a-zA-Z0-9_]*$ ]]
then
echo "$1: valid"
else
echo "$1: invalid"
fi
}