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

如何在bash函数中将bash变量代入yq命令

问题背景与报错说明

示例YAML文件example.yaml内容:

services:
test:
  item0:
  item1:
  item2:
  item3:

编写的bash递归遍历YAML层级函数:

function readYAML {
    local yaml="$1"
    declare -a arr
    readarray -t arr <<< "$(echo "$yaml" | yq -r '. |select(.) |  keys | .[]' )"
    echo "array -> ${arr[@]}"
    for item in "${arr[@]}"; do
        if [$item != ""]; then
            echo $(".$item'")
            yq -r $(".$item'") | readYAML;
        fi
    done
}

执行命令 readYAML "$(cat example.yaml)" 后,出现报错:

'.test': command not found

需求:调整 yq -r $(".$item'") | readYAML; 这一行,最终得到包含item0至item3的数组arr。

补充说明:

  • 已知arr会被覆盖(为简化问题已去除数组命名相关代码)。
  • 使用的是Go yq(Mike Farrah v4.31.2)。
修正方案

错误原因

$(".$item'") 是bash的命令替换语法,会将括号内的内容当作系统命令执行,而非作为yq的过滤参数,因此触发了.test不是命令的报错。

修改后的函数

function readYAML {
    local yaml="$1"
    declare -a arr
    readarray -t arr <<< "$(echo "$yaml" | yq -r '. | select(.) | keys | .[]' )"
    echo "array -> ${arr[@]}"
    for item in "${arr[@]}"; do
        if [ "$item" != "" ]; then
            echo ".$item"
            echo "$yaml" | yq -r ".$item" | readYAML
        fi
    done
}

关键修改点

  1. 修复if条件语法:给[和]添加空格,同时给变量$item加双引号,避免空值或含特殊字符的变量导致语法错误。
  2. 移除错误的命令替换:直接用字符串.${item}构造yq的过滤表达式,无需命令替换语法。
  3. 补充yq的输入源:将当前传入的$yaml内容通过管道传给yq,确保yq能正确处理对应层级的内容,再递归调用函数。

执行效果

运行修正后的函数后,会输出以下内容,最终能得到包含item0至item3的数组arr:

array -> services test
.services
array -> 
.test
array -> item0 item1 item2 item3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:07:33