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
相关推荐
一只小灿灿1 天前
深入解析 Maven 与 Gradle:Java 项目构建工具的安装、使用
java·开发语言·maven
树在风中摇曳1 天前
C语言 | 文件操作详解与实战示例
c语言·开发语言
njsgcs1 天前
excel提取长宽,进行排版导出ezdxf 装箱算法 贪婪 总利用率91%
开发语言·python·excel
lsx2024061 天前
Memcached stats sizes 命令详解
开发语言
吃不饱的得可可1 天前
C++17常用新特性
开发语言·c++
西游音月1 天前
(4)框架搭建:Qt实战项目之主窗体介绍
开发语言·qt
leo__5201 天前
MATLAB实现图像超分辨率方法
开发语言·matlab
say_fall1 天前
C语言编程实战:每日刷题 - day 1
c语言·开发语言·学习
没有bug.的程序员1 天前
Spring Cloud Bus 事件广播机制
java·开发语言·spring boot·hystrix·feign·springcloudbus·事件广播机制