4 bash
是否可以在bash中创建一个对象数组?
这就是我的尝试:
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
Run Code Online (Sandbox Code Playgroud)
显然,这不起作用,我找不到如何实现,因为我没有找到bash对象.
Ben*_* W. 18
您可以使用关联数组(在Bash 4.0中引入)和namerefs(参见手册declare和Shell参数的第一段- 在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
Run Code Online (Sandbox Code Playgroud)
这打印
Email: test@abc.com
Password: admin123
Email: test@xyz.org
Password: passwd1!
Run Code Online (Sandbox Code Playgroud)
declare -A 声明一个关联数组.
诀窍是将所有"对象"(关联数组)变量名称分配给相同的前缀,例如identification.该${!prefix@}符号扩展到开头的所有变量名prefix:
$ var1=
$ var2=
$ var3=
$ echo ${!var@}
var1 var2 var3
Run Code Online (Sandbox Code Playgroud)
然后,要访问关联数组的键值对,我们使用nameref属性声明for循环的控制变量:
declare -n identification
Run Code Online (Sandbox Code Playgroud)
这样循环
for identification in ${!identification@}; do
Run Code Online (Sandbox Code Playgroud)
使identification行为好像它是扩展的实际变量${!identification@}.
尽管如此,在以下情况下做一些事情会更容易:
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
Run Code Online (Sandbox Code Playgroud)
即,只需遍历包含您的信息的两个数组.
我倾向于使用 json 来创建对象。对我来说,这使它变得非常简单和灵活。
这是一个过于简单的例子。
我创建一个 json 文件:devices.json
{
"backup" : [{
"addr":"192.168.1.1",
"username":"backuper",
"dstfile":"firewallconfig",
"ext":".cfg",
"method":"ssh",
"rotate":"no",
"enabled":"yes"
}, {
"addr":"192.168.1.2",
"username":"backuper",
"dstfile":"routerconfig",
"ext":".cfg",
"method":"ssh",
"rotate":"no",
"enabled":"yes"
}]
}
Run Code Online (Sandbox Code Playgroud)
Bash 脚本:task.sh
# read the devices.json file and store it in the variable jsonlist
jsonlist=$(jq -r '.backup' "devices.json")
# inside the loop, you cant use the fuction _jq() to get values from each object.
for row in $(echo "${jsonlist}" | jq -r '.[] | @base64'); do
_jq()
{
echo ${row} | base64 --decode | jq -r ${1}
}
echo "backing up: $(_jq '.addr')"
echo "using method: $(_jq '.method')"
done
Run Code Online (Sandbox Code Playgroud)
发布原始帖子的人可以通过谷歌搜索“using json with bash”或其他东西找到。
| 归档时间: |
|
| 查看次数: |
6528 次 |
| 最近记录: |