Home > front end >  Set only last variable to file
Set only last variable to file

Time:03-03

In bash use jq to parse 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

And here output:

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

But on file $FILE_REPORT_RULES saved only last value = 120 :

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

CodePudding user response:

You are sequentially writing to the same file but always using the unaltered input $RULES_REPORT_INIT_JSON. This makes you see only the last change.

Instead of writing to the file on each iteration, you could save the changes to the variable and write to the file just once in the end:

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

Or, if $RULES_REPORT_INIT_JSON needs to stay unaltered throughout the loop, use a temporary variable instead

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