Bash throwing errors when parsing a JSON field with empty lines to env var: Invalid environment variable format ' '

I’m saving a JSON field, .body, to an ENV variable. The content of this field will always be changing with multiple strings and characters, it’s the body message of a Pull Request in GitHub. So markdown will also get passed:

Below would be an accurate example extracted from .body

#Title

## SubTitle

*date*

1. Item 1
2. Item 2
3. Item 3

When I parse the JSON using jq and -r for its raw content:

echo "PR_BODY=$(jq -r '.body' $HOME/pr.json)" >> $GITHUB_ENV

I get errors from GitHub actions:

enter image description here

For reference, my plan is to save .body data into a markdown file like so after managing to save it to an env variable:

      run: |
        ed changelog.md <<'END_ED'
        1i

        ${{ env.PR_BODY }}

        .
        wq
        END_ED
        echo >> changelog.md

How can I go about extracting the data in .body without empty spaces throwing errors? Perhaps an ENV variable is not the way to go about this?

EDIT:
Here is an original raw JSON in the .body:

"body": "Manually configuring ports for DEV, CAT/QA environments. Migrating from managed service to self-serve "GCP resource". rnrn- [x] DEVrn- [x] CAT/QArn- [ ] PRODrnrn```rn# Allow healthcheck on ports 80, 443rnresource "google_compute_firewall" "allow-healthcheck" {rn  name = "${format("%s","${var.gcp_resource_name}-${var.gcp_env}-fw-allow-healthcheck")}"rn  network = "${google_compute_network.vpc.name}"rn  allow {rn    protocol = "tcp"rn    ports    = ["80","443"]rn  }rn  source_ranges = ["2.2.0.0/16", "1.1.0.0/22"]rn}rn```rnConfiguring for bug, link here:rn[Link To Terraform provider update](https://www.terraform.io/)"
Asked By: andres

||

Based on "Workflow commands for GitHub Actions", it looks like the syntax for multiline
values in $GITHUB_ENV would be something like:

PR_BODY<<EOF
multiline string
here
...
EOF

With the value coming from the command substitution you had there, you could produce that from the shell with e.g.:

printf "PR_BODY<<EOFn%snEOFn" "$(jq -r '.body' $HOME/pr.json)"

(You most likely want to use printf instead of echo there, since it makes it easier to insert newlines while not mangling the data from the command substitution. See Why is printf better than echo? for discussion.)

Answered By: ilkkachu
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.