[SOLVED] How to avoid bash/shell skipping quotation in variable value?

Issue

I have set a variable like this below-

domain= ("*.abc" "*.xyz" "*.123")

I want set the value of this variable in a json file like below-

"Items": [
            "*.abc",
            "*.xyz",
            "*.123",]

But, the problem is bash script is skipping quotation "" and taking only inside the quotation. Other than this, bash is also trying to take the value as command. I just want to set the value in Items array including commas, that’s it.

I am using jq --arg e1 ${domain[@]} to set the domain variable to e1 environment variable.

And getting this below error –

jq: error: syntax error, unexpected '*', expecting $end (Windows cmd shell quoting issues?) at <top-level>, line 1: *.xyz.com

Solution

You could turn the bash array into a string and separate the items by, say, a newline character, then import the string using --arg, and split it up again into a jq array using /:

jq -n --arg e1 "$(printf '%s\n' "${domain[@]}")" '{Items: ($e1 / "\n")}'
{
  "Items": [
    "*.abc",
    "*.xyz",
    "*.123"
  ]
}

Answered By – pmf

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published.