Home > Enterprise >  How to avoid bash/shell skipping quotation in variable value?
How to avoid bash/shell skipping quotation in variable value?

Time:06-22

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

CodePudding user response:

--arg doesn't understand bash arrays (some shells don't have any arrays).

You can use --args instead which populates $ARGS.positional with a list of remaining arguments.

domain=("*.abc" "*.xyz" "*.123")
jq '.Items = $ARGS.positional' <<<'{"Items":[]}' --args "${domain[@]}"

Note that I removed the space after domain=. With the space, bash throws a syntax error.

CodePudding user response:

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"
  ]
}

CodePudding user response:

You can use --args to pass the array to jq as arguments, preserving the list/array structure:

domain=('*.abc' '*.xyz' '*.123')
jq -n --args '.Items = $ARGS.positional' "${domain[@]}"

Gives:

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

Note that all the quoting is for the shell, not for the JSON. jq adds the quotes in the JSON. Add > myfile to jq to redirect the output to a file.

You can also skip the array and write '*.123' and so on directly, as arguments to jq.

  • Related