我有一个 yaml 文件,名为“test.yaml”。以下是yaml文件的内容。
...
test:
config:
abc: name1
xyz: name2
...
Run Code Online (Sandbox Code Playgroud)
现在我想从 shell 脚本内的 yaml 中单独读取 abc 和 xyz 的值,并将其存储在 shell 脚本内的两个变量中。test.yaml 文件包含除上述数据之外的其他数据,我不需要在这个 shell 脚本中关心这些数据。
例如:test.sh
var1=name1 //test[config[abc]]
var2=name2 //test[config[xyz]]
Run Code Online (Sandbox Code Playgroud)
如何从 shell 脚本内的 yaml 读取特定数据(作为键值)。如果有人帮助我解决这个问题,那将会非常有帮助。提前致谢!!!
这是yq的示例。以下所有内容均假设这些值不包含换行符。
给定
$ cat test.yaml
---
test:
config:
abc: name1
xyz: name2
Run Code Online (Sandbox Code Playgroud)
然后
yq e '.test.config | to_entries | map(.value) | .[]' test.yaml
Run Code Online (Sandbox Code Playgroud)
输出
name1
name2
Run Code Online (Sandbox Code Playgroud)
您可以将它们读入变量中,例如
{ read -r var1; read -r var2; } < <(yq e '.test.config | to_entries | map(.value) | .[]' test.yaml)
declare -p var1 var2
Run Code Online (Sandbox Code Playgroud)
declare -- var1="name1"
declare -- var2="name2"
Run Code Online (Sandbox Code Playgroud)
不过,我会将它们读入带有 yaml 键的关联数组中:
declare -A conf
while IFS="=" read -r key value; do conf["$key"]=$value; done < <(
yq e '.test.config | to_entries | map([.key, .value] | join("=")) | .[]' test.yaml
)
declare -p conf
Run Code Online (Sandbox Code Playgroud)
declare -A conf=([abc]="name1" [xyz]="name2" )
Run Code Online (Sandbox Code Playgroud)
然后你可以写
echo "test config for abc is ${conf[abc]}"
# or
for var in "${!conf[@]}"; do printf "key %s, value %s\n" "$var" "${conf[$var]}"; done
Run Code Online (Sandbox Code Playgroud)
我正在使用“Go 实现”
$ yq --version
yq (https://github.com/mikefarah/yq/) version 4.16.1
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7212 次 |
最近记录: |