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
相关推荐
‿hhh12 分钟前
学习笔记整理(部分)
java·开发语言·笔记·学习·mvc
HappRobot18 分钟前
Python 面向对象
开发语言·python
JIngJaneIL20 分钟前
基于Java + vue干洗店预约洗衣系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
dllmayday1 小时前
Qt/QML + C++ 双向数据绑定(MVVM 模式的几种常用方法(ChatGPT)
开发语言·c++·qt
han_hanker1 小时前
统一拦截异常 @RestControllerAdvice
java·开发语言·数据库
liu****1 小时前
一.脚手架介绍以及部分工具使用
开发语言·数据结构·c++·手脚架开发
资深web全栈开发1 小时前
深入理解 Google Wire:Go 语言的编译时依赖注入框架
开发语言·后端·golang
ohoy1 小时前
EasyPoi 数据脱敏
开发语言·python·excel
Hello World呀1 小时前
Java实现手机号和身份证号脱敏工具类
java·开发语言
曹牧1 小时前
Java:serialVersionUID
java·开发语言