You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用函数时无法从Unix Bash关联数组中提取值

Bash关联数组函数调用取值失败的解决方法

问题根源

你的代码存在两个核心问题:

  1. get-value函数逻辑错误:
    • 函数第一行直接printf "$1\n"输出传入的键名,导致外部用$()捕获的结果就是键名而非数组值
    • 引用数组值时依赖未在函数内定义的全局变量$id_key,而非函数的输入参数$1
  2. 命名冲突:初始化函数名my_ids和关联数组名my_ids重名,属于不良实践,会导致后续无法直接通过my_ids引用数组

修正后的脚本

修正stk1.sh

#!/bin/bash
declare -x -A my_ids

# 重命名初始化函数,避免和数组名冲突
function init_my_ids {
  my_ids[cat]=100
  my_ids[dog]=200
  echo "Length of Array :${#my_ids[*]}"
  echo "*** Now printing the contents of the Array ...."
  for x in "${!my_ids[@]}"
  do
    printf "$x  ${my_ids[$x]} \n"
  done
}
init_my_ids

function get-value {
  # 仅返回对应键的数组值
  if [[ -n "$1" ]]; then
    echo "${my_ids[$1]}"
  fi
}

stk2.sh无需修改

#!/bin/bash
 
source stk1.sh
id_key=${1:-cat}  ## setting default
echo "Id key is :${id_key}"
id_no=$(get-value $id_key)
echo "Value is ### ${id_no}"

运行结果

./stk2.sh dog
Length of Array :2
*** Now printing the contents of the Array ....
dog  200 
cat  100 
Id key is :dog
Value is ### 200

修正说明

  1. 解决命名冲突:将初始化函数重命名为init_my_ids,避免和数组名冲突,确保数组可以被正常引用
  2. 修复取值函数逻辑:
    • 删除直接输出键名的语句,消除返回结果错误的根源
    • 使用函数输入参数$1作为数组键,不再依赖全局变量,让函数逻辑更独立可靠
    • 通过echo输出数组对应的值,确保外部能捕获到正确的数值

内容的提问来源于stack exchange,提问作者Judi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 15:16:59