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

使用yq读取YAML键时处理空值(null)报错的解决方案

处理YAML空值键并转为Bash布尔变量

现有example.yaml内容如下:

test:
services:
  registry:
    image: registry:2
    ports:
      - "5000:5000"
      - "337:337"
  pinger:
    build:

读取services的键到Bash数组可使用以下命令:

readarray -t services <<< $(yq e '.services | keys | .[]' example.yaml)

但读取test这类对应值为null的键时,执行yq e '.test | keys | .[]' example.yaml会报错:

Error: Cannot get keys of !!null, keys only works for maps and arrays

要将空值场景替换为false并存入Bash变量,可通过yq的条件判断实现:

test_value=$(yq e '.test | if . == null then false else . end' example.yaml)

执行后,test_value变量的值即为false。后续在Bash脚本中可通过[ "$test_value" = "false" ]进行布尔判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 11:03:25