bash 在bash中创建对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38794449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating array of objects in bash
提问by Benjamin W.
Is it possible to create an array of objects in bash?
是否可以在 bash 中创建对象数组?
That's how I'm trying:
这就是我正在尝试的方式:
declare -a identifications=(
{
email = '...',
password = '...'
}
)
declare -a years=(
'2011'
'2012'
'2013'
'2014'
'2015'
'2016'
)
for identification in "${identifications[@]}"
do
for year in "${years[@]}"
do
my_program --type=CNPJ --format=XLS --identification=${identification.email} --password=${identication.password} --competence=${year} --output="$identification - $year"
done
done
Obviously, this doesn't work, and I'm not finding how to achieve that, since I'm not finding bash objects.
显然,这不起作用,我没有找到如何实现这一点,因为我没有找到 bash 对象。
回答by Benjamin W.
You could do some trickery with associative arrays(introduced in Bash 4.0) and namerefs (see manual for declare
and the first paragraph of Shell Parameters– introduced in Bash 4.3):
您可以使用关联数组(在 Bash 4.0 中引入)和 namerefs(参见手册declare
和Shell 参数的第一段- 在 Bash 4.3 中引入)来做一些技巧:
#!/bin/bash
declare -A identification0=(
[email]='[email protected]'
[password]='admin123'
)
declare -A identification1=(
[email]='[email protected]'
[password]='passwd1!'
)
declare -n identification
for identification in ${!identification@}; do
echo "Email: ${identification[email]}"
echo "Password: ${identification[password]}"
done
This prints
这打印
Email: [email protected]
Password: admin123
Email: [email protected]
Password: passwd1!
declare -A
declares an associative array.
declare -A
声明一个关联数组。
The trick is to assign all your "objects" (associative arrays) variable names starting with the same prefix, like identification
. The ${!prefix@}
notation expands to all variable names starting with prefix
:
诀窍是为所有“对象”(关联数组)变量名分配以相同前缀开头,例如identification
. 该符号扩展到所有以 开头的变量名:${!prefix@}
prefix
$ var1=
$ var2=
$ var3=
$ echo ${!var@}
var1 var2 var3
Then, to access the key-value pairs of the associative array, we declare the control variable for the for loop with the nameref attribute:
然后,为了访问关联数组的键值对,我们使用 nameref 属性声明 for 循环的控制变量:
declare -n identification
so that the loop
这样循环
for identification in ${!identification@}; do
makes identification
behave as if it were the actual variable from the expansion of ${!identification@}
.
make 的identification
行为就好像它是${!identification@}
.
In all likelihood, it'll be easier to do something like the following, though:
不过,很可能执行以下操作会更容易:
emails=('[email protected]' '[email protected]')
passwords=('admin123' 'passwd1!')
for (( i = 0; i < ${#emails[@]}; ++i )); do
echo "Email: ${emails[i]}"
echo "Password: ${passwords[i]}"
done
I.e., just loop over two arrays containing your information.
即,只需循环包含您的信息的两个数组。