BASH:如何通过从字符串数组作为参数的命令? [英] BASH: How to pass strings from array as arguments to a command?

查看:148
本文介绍了BASH:如何通过从字符串数组作为参数的命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在list_of_arrays,每个字符串是一个数组,我需要传递给'声明'的命令行的名称。

Each string in "list_of_arrays", is the name of an array I need to pass to the 'declare' command line.

是这样的:

for arrayname in "${list_of_arrays[@]}"; do 
declare -A idx=(["$arrayname[0]"]=0 ["$arrayname[1]"]=0 ["$arrayname[2]"]=0 ...)
done

我如何使这项工作任何数量的字符串?每个字符串/数组名称将永远是独一无二的。

How do I make this work for any number of strings? Each string/array name will always be unique.

推荐答案

您需要使用的间接变量来做到这一点:

You'll need to use indirect variables to accomplish this:

foo=(a b c)
baz=(g h i)
bar=(d e f)
list_of_arrays=(foo bar baz)
for aname in "${list_of_arrays[@]}"; do 
    unset idx; declare -A idx
    tmp="${aname}[@]"
    for value in "${!tmp}"; do 
        idx[$value]=0
    done
    # print it out to verify
    declare -p idx
done

declare -A idx='([a]="0" [b]="0" [c]="0" )'
declare -A idx='([d]="0" [e]="0" [f]="0" )'
declare -A idx='([g]="0" [h]="0" [i]="0" )'


好了,以上所有是错误的,因为OP希望阵列的名称的是 IDX 阵的钥匙。正如在评论中提到:


Well, all of the above is wrong, as the OP wants the array names to be the keys of the idx array. As mentioned in the comments:

tmp=( "${list_of_arrays[@]/#/[}" ) 
tmp=( "${tmp[@]/%/]=0}" )
eval declare -A idx=( "${tmp[@]}" )

虽然我会去的聪明得多:

Although I would go with the much less clever:

declare -A idx
for aname in "${list_of_arrays[@]}"; do idx["$aname"]=0; done
declare -p idx

这篇关于BASH:如何通过从字符串数组作为参数的命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆