使用嵌套 for 循环通过 bash 数组进行受控迭代

Controlled Iteration through bash array using nested for loop

common.yml 文件

tomcat9_version:               "9.0.64-154"
openjdk11_version:                "11.54.24-95"
newrelic_infra_agent_version:  "0.1.22-42"

vars.yml

Tomcat:
  packages:
    OpenJDK11:
      - 11.52.24
    Tomcat9:
      - 9.0.50
   newrelic_infra:
      - 0.1.21

从common.yml中获取tomcat9_version、openjdk11_version、newrelic_infra_agent_version的值并替换vars.yml中的OpenJDK11、Tomcat9、newrelic_infra值

我写的

#!/bin/bash
declare -a arr=("openjdk11_version" "tomcat9_version" "newrelic_infra_agent_version")
declare -a brr=("OpenJDK11:" "Tomcat9:" "newrelic_infra:")
for i in "${arr[@]}"
do
   value=$(grep "$i" common.yaml  | awk '{print $NF}')
   echo "$value"
    for i in "${brr[@]}"
    do
      pakru=$(awk -v var=$i ' == "-"{ if (key == var) print $NF;next } {key=}' vars.yaml)
      echo "$pakru"
      sed -i "s/$pakru/$value/g" "vars.yaml"
      break
   done
done

我得到的输出

"11.54.24-95"
11.52.24
9.0.50
0.1.21
"9.0.64-154"
11.52.24
9.0.50
0.1.21
"0.1.22-42"
11.52.24
9.0.50
0.1.21

预期输出:-

"11.54.24-95"
11.52.24
"9.0.64-154"
9.0.50
"0.1.22-42"
0.1.21

使用像 yq 这样的专门工具可以帮助处理带有 shell:

的 YAML
yq eval-all '
    select(fi == 0) as $common |
    select(fi == 1) |                                
    .Tomcat.packages.OpenJDK11[0] = $common.openjdk11_version |
    .Tomcat.packages.Tomcat9[0] = $common.tomcat9_version |
    .Tomcat.packages.newrelic_infra[0] = $common.newrelic_infra_agent_version
' common.yml vars.yml
Tomcat:
  packages:
    OpenJDK11:
      - "11.54.24-95"
    Tomcat9:
      - "9.0.64-154"
    newrelic_infra:
      - "0.1.22-42"

想通了

#!/bin/bash
declare -a arr=("openjdk11_version" "tomcat9_version" "newrelic_infra_agent_version")
declare -a brr=("OpenJDK11:" "Tomcat9:" "newrelic_infra:")
for ((i=0; i<${#arr[@]}; i++))
do
   value=$(egrep "${arr[$i]}" common.yaml  | awk '{print $NF}' | uniq | cut -d '-' -f1 | tr -d '"')
   echo "$value"
   pakru=$(awk -v var=${brr[$i]} ' == "-"{ if (key == var) print $NF;next } {key=}' vars.yaml)
   echo "$pakru"
   sed -i "s/$pakru/$value/g" "vars.yaml"
done