简体   繁体   English

Bash 命令检查变量名是否合法

[英]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...依此类推,变量名称只能包含字母、数字(但不能在开头),.. 就像 java 的所有规则一样...

Is there any function that I can use?我可以使用 function 吗? I do not want to reinvent the wheel...我不想重新发明轮子...

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
}

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. 对于bash变量的上下文, dogbane的答案几乎已完成,但它尚未更新以反映包含完全有效验证器的最终注释。 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. 这个答案提供了一个函数,该函数对所有有效名称求值为true,并且可以用作条件而不是返回必须与某些东西进行比较的值。 Plus, it can be used across multiple shells. 此外,它可以跨多个shell使用。


The function: 功能:

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


Example usage in bash: bash中的示例用法:

key=...
value=...

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


# or it might simply look like this

isValidVarName "$key" && eval "$key=\"$value\""

Bash only:仅限 Bash:

isvalidvarname ()
{
    local varname;
    local regexp_varname='^[_[:alpha:]][_[:alpha:][:digit:]]*$';
    varname="$1";
    [[ "${varname}" =~ ${regexp_varname} ]]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM