Bash 中的多维数组 [英] Multi-dimensional arrays in Bash

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

问题描述

我正在计划一个脚本来管理我的 Linux 系统的某些部分,并且正在决定是否要使用 .

I am planning a script to manage some pieces of my Linux systems and am at the point of deciding if I want to use bash or python.

我更喜欢将其作为 Bash 脚本执行,因为命令更简单,但真正的决定因素是配置.我需要能够在配置文件中存储一个多维数组来告诉脚本如何处理它自己.使用 bash 在配置文件中存储简单的键=值对很容易,但我能想到的做多维数组的唯一方法是两层解析引擎,比如

I would prefer to do this as a Bash script simply because the commands are easier, but the real deciding factor is configuration. I need to be able to store a multi-dimensional array in the configuration file to tell the script what to do with itself. Storing simple key=value pairs in config files is easy enough with bash, but the only way I can think of to do a multi-dimensional array is a two layer parsing engine, something like

array=&d1|v1;v2;v3&d2|v1;v2;v3

但是 marshall/unmarshall 代码可能会变得很笨拙,对于下一个必须管理它的可怜的 sap 来说,它远非用户友好.如果我不能在 bash 中轻松做到这一点,我将简单地将配置写入 xml 文件并在 python 中编写脚本.

but the marshall/unmarshall code could get to be a bear and its far from user friendly for the next poor sap that has to administer this. If i can't do this easily in bash i will simply write the configs to an xml file and write the script in python.

有没有一种简单的方法可以在 bash 中做到这一点?

Is there an easy way to do this in bash?

谢谢大家.

推荐答案

Bash 不支持多维数组,也不支持散列,而且您似乎想要一个值是数组的散列.这个方案不是很漂亮,有xml文件的方案应该更好:

Bash does not support multidimensional arrays, nor hashes, and it seems that you want a hash that values are arrays. This solution is not very beautiful, a solution with an xml file should be better :

array=('d1=(v1 v2 v3)' 'd2=(v1 v2 v3)')
for elt in "${array[@]}";do eval $elt;done
echo "d1 ${#d1[@]} ${d1[@]}"
echo "d2 ${#d2[@]} ${d2[@]}"

这个答案已经很老了,因为 bash 4 支持哈希表,另见 这个答案 没有 eval 的解决方案.

this answer is quite old, since since bash 4 supports hash tables, see also this answer for a solution without eval.

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

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