使用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
相关产品推荐
相关产品推荐

