Bash检查变量数组是否具有值

时间:2020-02-28 09:29:12

标签: bash shell

我有一个变量数组。我想使用for循环检查变量是否具有值。

我正在将值放入循环,但是if条件失败

function check {
    arr=("$@")
    for var in "${arr[@]}"; do
        if [ -z $var ] ; then
            echo $var "is not available"
        else
            echo $var "is available"
        fi
    done
}

name="abc"
city="xyz"
arr=(name city state country)
check ${arr[@]}

对于上述内容,我将全部获得可用

预期输出为

name is available
city is available
state is not available
country is not available

2 个答案:

答案 0 :(得分:4)

这是您任务的正确语法

if [ -z "${!var}" ] ; then
    echo $var "is not available"
else
    echo $var "is available"
fi

说明,此方法使用间接变量扩展,此构造${!var}将扩展为名称在$var中的变量的值。

更改了check功能

check () {
    for var in "$@"; do
        [[ "${!var}" ]] && not= || not="not "
        echo "$var is ${not}available"
    done
}

另一个使用declare

的变体
check () {
    for var in "$@"; do
        declare -p $var &> /dev/null && not= || not="not "
        echo "$var is ${not}available"
    done
}

declare帮助下

$ declare --help
declare: declare [-aAfFgilnrtux] [-p] [name[=value] ...]
    Set variable values and attributes.
    Declare variables and give them attributes.  If no NAMEs are given,
    display the attributes and values of all variables.
    ...
    -p  display the attributes and value of each NAME
    ...

实际上,可以使用此功能一次检查所有变种

check () {
    declare -p $@ 2>&1 | sed 's/.* \(.*\)=.*/\1 is available/;s/.*declare: \(.*\):.*/\1 is not available/'
}

答案 1 :(得分:0)

虽然间接寻址是一种可能的解决方案,但使用not really recommended。一种更安全的方法是使用关联数组:

function check {
    eval "declare -A arr="${1#*=}
    shift
    for var in "$@"; do
        if [ -z "${arr[$var]}" ] ; then
            echo $var "is not available"
        else
            echo $var "is available"
        fi
    done
}

declare -A list
list[name]="abc"
list[city]="xyz"

check "$(declare -p list)" name city state country

这将返回:

name is available
city is available
state is not available
country is not available

以下问题用于创建此答案: How to rename an associative array in Bash?