0

We need to use the variable $domain_name instead of the hyb.com string in the following jq command:

jq --argjson IDS '['"$(seq -s, -f'"car%02.0f_hyb.com"' 11)"']' '
  .mazda |= $IDS
' file.json

When we just set the variable as

export domain_name=_hyb.com

jq --argjson IDS '['"$(seq -s, -f'"car%02.0f$domain_name "' 11)"']' '
  .mazda |= $IDS
' file.json

Then the exported variable domain_name is not see by jq. Are there any suggestion of how to import the variable into jq?

Kusalananda
  • 333,661
yael
  • 13,106

2 Answers2

3

You are using $domain_name in single quotes. This is why the shell is not expanding the variable.

In this case, though, I would suggest doing it a slightly different way:

jq provides safe ways to import raw data from the shell:

jq '.mazda |= $ARGS.positional' file.json --args car{00..11}"$domain_name"

This would insert the mazda key with the values taken from the list after --args on the command line. The --args and the list of values should be last on the command line. The values will be JSON-encoded as by jq if needs be. This is usually better than trying to create correct JSON yourself from data that may come from external sources (for example, if the data that you want to insert contains tabs or newlines or double quotes, jq will encode these properly as JSON strings with --args).

The list is generated using a brace expansion. Assuming you are using bash release 4 or later, the numbers generated by {00..11} would be properly zero-filled.

Note that domain_name does not need to be an environment (exported) variable.

Kusalananda
  • 333,661
1

I think your main issue is that you don't use the variable in the input to jq - you use it as the input to seq.

That being said, @muru's comment is correct, as well as pointing to the question "Is there any way to print value inside variable inside single quote?" - which you've already demonstrated that you know how to use: you have used it in escaping the output of seq into the jq argument.

But your problem can be solved in a much easier way, because you don't actually need to use a single quote in the seq input: you only think you do because you want to use double quotes in the input value, but you can easily escape those:

seq -s, -f "\"car%02.0f${domain_name}\"" 11
Guss
  • 12,628