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

你可能感兴趣的:(bash,开发语言)