如何将关联数组作为参数传递给函数?这可能在Bash吗
以下代码无法正常工作:
function iterateArray { local ADATA="${@}" # associative array for key in "${!ADATA[@]}" do echo "key - ${key}" echo "value: ${ADATA[$key]}" done }
将关联数组传递给类似正常数组的函数不起作用:
iterateArray "$A_DATA"
要么
iterateArray "$A_DATA[@]"
上周我有同样的问题,想了好一会儿。
看来,关联数组不能被序列化或复制。有一个很好的Bash常见问题条目,关联数组,explains them in detail.最后一节给了我以下的想法,对我有用:
function print_array { # eval string into a new assocociative array eval "declare -A func_assoc_array="${1#*=} # proof that array was successfully created declare -p func_assoc_array } # declare an assocociative array declare -A assoc_array=(["key1"]="value1" ["key2"]="value2") # show assocociative array definition declare -p assoc_array # pass assocociative array in string form to function print_array "$(declare -p assoc_array)"