在linux bash中map是作为数组处理的,不能作为参数直接传递函数,如果一定要传递给函数,要做一些变通处理,示例如下:
#!/bin/bash
function test_map()
{
# 获取map变量的声明字符串
# 在本例中为:declare -A user='([name]="tom" [age]="15" [sex]="male" )'
local var=$(declare -p "$1")
# 截取=号后的部分: '([name]="tom" [age]="15" [sex]="male" )'
# 重新创建一个临时map变量ref
eval "declare -A local ref"=${var#*=}
# 输出所有的key
echo keys:${!ref[@]}
# 输出所有的value
echo values:${ref[@]}
}
# 定义一个map变量
declare -A user=(['name']='tom' ['age']='15')
# 再添加一个映射
user[sex]=male
# 将参数名传递给函数
test_map user
参考资料:
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有