首页 > 解决方案 > 数组内的bash变量扩展

问题描述

如何从数组列表中的变量传递值。

下面的代码有效,它将 repo_libs 元素分配给 repo_list。有没有办法从变量中读取值以在数组列表中形成数组名称。

 if [[ "$service" == "all" || "$service" == "libs" ]] ; then
    # below working        
    repo_list=("${repo_libs[@]}")
        echo "repo_list : ${repo_list[*]}"
 fi

寻找如下陈述

repo_list=(${repo_`echo $service`[@]})
repo_list=("${repo_$service[@]}")

看到如下错误。

./build.sh: line 168: ${repo_`echo $service`[@]}: bad substitution
./build.sh: line 173: ${repo_$service[@]}: bad substitution

[编辑] 这是使用 if .. else 作为我正在使用的替代方法的代码。

 if [ "$service" = "all" ] ; then
        repo_list=("${repo_all[@]}")
 elif [ "$service" = "libs" ] ; then
        repo_list=("${repo_libs[@]}")
 elif [ "$service" = "portlets" ] ; then
        repo_list=("${repo_portlets[@]}")
 else
        repo_list=("$service")
 fi

标签: arraysbashshellscriptingvariable-expansion

解决方案


推荐阅读