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. bash通过变量内容获取对应关联数组

    2023-12-06 09:14:05       49 阅读
  2. vue获取剪切板内容

    2023-12-06 09:14:05       25 阅读
  3. bash通配符小结

    2023-12-06 09:14:05       30 阅读
  4. axios无法获取response headers内容

    2023-12-06 09:14:05       57 阅读
  5. 6、掌握对象内存分配与变迁

    2023-12-06 09:14:05       36 阅读
  6. 去除Bash 变量空白字符 —— 筑梦之路

    2023-12-06 09:14:05       61 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-06 09:14:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-06 09:14:05       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-06 09:14:05       82 阅读
  4. Python语言-面向对象

    2023-12-06 09:14:05       91 阅读

热门阅读

  1. 计算机网络——应用层

    2023-12-06 09:14:05       58 阅读
  2. 大型语言模型在实体关系提取中的应用探索(二)

    2023-12-06 09:14:05       55 阅读
  3. JeecgBoot 框架升级至 Spring Boot3 的实战步骤

    2023-12-06 09:14:05       48 阅读
  4. 采用Python 将PDF文件按照页码进行切分并保存

    2023-12-06 09:14:05       55 阅读
  5. GoLang语言Map用法

    2023-12-06 09:14:05       54 阅读
  6. Usergolang 一些优质关于sip协议包

    2023-12-06 09:14:05       57 阅读