仅将最后一个变量设置为文件

Set only last variable to file

在bash中使用jq解析json。

  for currentActivation in ${ACTIVATION_ARRAY[@]}; do
      rulesResponse=$(curl -s -XGET "$RULES_REQUEST_URL_PREFIX&activation=$currentActivation&types=$rulesTypeKey&p=1&ps=1")
      typeRuleTotal=$(jq -r '.total' <<< "$rulesResponse")
      echo "current_rulesTypeKey = $rulesTypeKey, typeRuleTotal = $typeRuleTotal"
      jq --argjson totalArg "$typeRuleTotal" --arg currentType "$rulesTypeKey" '.rules.active[$currentType] = $totalArg ' <<<$RULES_REPORT_INIT_JSON >$FILE_REPORT_RULES
  done

这里输出:

current_rulesTypeKey = CODE_SMELL, typeRuleTotal = 310
current_rulesTypeKey = SECURITY_HOTSPOT, typeRuleTotal = 1
current_rulesTypeKey = BUG, typeRuleTotal = 304
current_rulesTypeKey = VULNERABILITY, typeRuleTotal = 120

但是在文件 $FILE_REPORT_RULES 上只保存了最后一个值 = 120 :

{
  "rules": {
    "totalActive": 0,
    "totalInactive": 0,
    "active": {
      "BUG": 0,
      "VULNERABILITY": 120,
      "CODE_SMELL": 0,
      "SECURITY_HOTSPOT": 0
    }
  }
}

您正在连续写入同一个文件,但始终使用未更改的输入 $RULES_REPORT_INIT_JSON。这使您只能看到最后的更改。

您可以保存对变量的更改并在最后只写入一次文件,而不是每次迭代都写入文件:

for …; do
  …
  RULES_REPORT_INIT_JSON="$(jq … <<<$RULES_REPORT_INIT_JSON)"
  …
done
cat <<<$RULES_REPORT_INIT_JSON >$FILE_REPORT_RULES

或者,如果 $RULES_REPORT_INIT_JSON 需要在整个循环中保持不变,请改用临时变量

temp="$RULES_REPORT_INIT_JSON"
for …; do
  …
  temp="$(jq … <<<$temp)"
  …
done
cat <<<$temp >$FILE_REPORT_RULES