推广网站怎么做模板,网络推广的网站,app与移动网站开发资料,页面模板发布后再添加文章怎么办bash中通过变量中的内容获取对应的关联数组
Bash declare 手册#xff1a; https://phoenixnap.com/kb/bash-declare
实际问题#xff1a;
在 bash 中创建了多个关联数组#xff0c;需要根据输入的值#xff0c;获取不同的关联数组。 可以使用 if 进行多次判断#xff…bash中通过变量中的内容获取对应的关联数组
Bash declare 手册 https://phoenixnap.com/kb/bash-declare
实际问题
在 bash 中创建了多个关联数组需要根据输入的值获取不同的关联数组。 可以使用 if 进行多次判断但是效率低且代码显得很臃肿。 希望可以根据根据输入的值组成关联数组的名字然后通过该名字拿到数组的内容
解决方法
#!/bin/bash
# vim: ts4 sw4 sts4 et:# 定义关联数组
declare -A A_LIST
declare -A B_LIST
A_LIST[1]A_1
A_LIST[2]A_2B_LIST[1]B_1
B_LIST[2]B_2#selectedA
selectedB
arr_name${selected}_LIST
declare -n selected_arr$arr_name# 通过间接引用遍历关联数组
for key in ${!selected_arr[]}; doecho $key: ${selected_arr[$key]}
done脚本运行输出为
$ ./test.sh
2: B_2
1: B_1