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[@]}"; doecho "$key: ${selected_arr[$key]}"
done
腳本運行輸出為:
$ ./test.sh
2: B_2
1: B_1