在bash中创建对象数组 [英] Creating array of objects in bash

查看:202
本文介绍了在bash中创建对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在bash中创建对象数组?

Is it possible to create an array of objects in 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

很显然,这是行不通的,而且由于找不到bash对象,因此我也没有找到实现该目标的方法.

Obviously, this doesn't work, and I'm not finding how to achieve that, since I'm not finding bash objects.

推荐答案

您可以使用关联数组(在Bash 4.0中引入)和名称引用(请参见 Shell参数(在Bash 4.3中引入):

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):

#!/bin/bash

declare -A identification0=(
    [email]='test@abc.com'
    [password]='admin123'
)
declare -A identification1=(
    [email]='test@xyz.org'
    [password]='passwd1!'
)

declare -n identification
for identification in ${!identification@}; do
    echo "Email: ${identification[email]}"
    echo "Password: ${identification[password]}"
done

此打印

Email: test@abc.com
Password: admin123
Email: test@xyz.org
Password: passwd1!

declare -A声明一个关联数组.

诀窍是分配所有以相同前缀开头的对象"(关联数组)变量名称,例如identification. ${!prefix@}表示法扩展为以 prefix 开头的所有变量名:

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:

$ var1=
$ var2=
$ var3=
$ echo ${!var@}
var1 var2 var3

然后,要访问关联数组的键值对,我们使用nameref属性声明for循环的控制变量:

Then, to access the key-value pairs of the associative array, we declare the control variable for the for loop with the nameref attribute:

declare -n identification

这样循环

for identification in ${!identification@}; do

使identification的行为就像是${!identification@}扩展中的实际变量一样.

makes identification behave as if it were the actual variable from the expansion of ${!identification@}.

尽管如此,执行以下类似操作会更容易:

In all likelihood, it'll be easier to do something like the following, though:

emails=('test@abc.com' 'test@xyz.org')
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.

这篇关于在bash中创建对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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