bash中通过变量中的内容获取对应的关联数组

bash中通过变量中的内容获取对应的关联数组

Bash declare 手册:

https://phoenixnap.com/kb/bash-declare

实际问题:

在 bash 中创建了多个关联数组,需要根据输入的值,获取不同的关联数组。

可以使用 if 进行多次判断,但是效率低且代码显得很臃肿。

希望可以根据根据输入的值,组成关联数组的名字,然后通过该名字拿到数组的内容

解决方法:

复制代码
#!/bin/bash
# vim: ts=4 sw=4 sts=4 et:

# 定义关联数组
declare -A A_LIST
declare -A B_LIST
A_LIST[1]="A_1"
A_LIST[2]="A_2"

B_LIST[1]="B_1"
B_LIST[2]="B_2"

#selected=A
selected=B
arr_name="${selected}_LIST"
declare -n  selected_arr=$arr_name

# 通过间接引用遍历关联数组
for key in "${!selected_arr[@]}"; do
  echo "$key: ${selected_arr[$key]}"
done

脚本运行输出为:

复制代码
$ ./test.sh
2: B_2
1: B_1
相关推荐
embrace991 天前
【C语言学习】结构体详解
android·c语言·开发语言·数据结构·学习·算法·青少年编程
无心水1 天前
【Python实战进阶】4、Python字典与集合深度解析
开发语言·人工智能·python·python字典·python集合·python实战进阶·python工业化实战进阶
代码不停1 天前
Java单链表和哈希表题目练习
java·开发语言·散列表
Dxxyyyy1 天前
零基础学JAVA--Day37(坦克大战1.0)
java·开发语言
u***u6851 天前
PHP在电商中的WooCommerce
开发语言·php
冠希陈、1 天前
PHP 过滤敏感词(含类库)
开发语言·php·内容敏感词
qq_401700411 天前
Qt Positioning 模块访问设备地理位置信息
开发语言·qt
1***s6321 天前
C++移动语义优化
开发语言·c++
m5655bj1 天前
使用 Python 高效复制 Excel 行、列、单元格
开发语言·python·excel
Murphy_lx1 天前
C++ std_stringstream
开发语言·c++·算法