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
相关推荐
临床数据科学和人工智能兴趣组3 小时前
在R语言中, 使用 as.factor() 函数转换数值型变量
开发语言·r语言
andyweike6 小时前
php笔记
开发语言·笔记·php
Circ.7 小时前
Python 调试 Litellm 本地大模型接口:模型列表与对话接口实操踩坑记录
开发语言·python
现任明教教主~9 小时前
Thinkphp站群蜘蛛池SaaS系统YanyvSEO含多用户/积分/六大引擎计费/易支付对接
java·开发语言·spring
Zhou1411369 小时前
SpringSecurity_02_授权与高级功能
开发语言·python
码匠许师傅10 小时前
【C++三方组件】cpp-httplib:一个头文件起 HTTP 服务
开发语言·c++·http
小小小小钰儿11 小时前
1.5-Python网络编程
开发语言·网络·python·web安全·计算机·网络安全
hiahiahia12311 小时前
实现完整 Tool Dispatcher
开发语言·前端