-1

I need to execute cat build.json | jq '.Stage*.Name' for 5 times, where * is a number from 1 to 5.

I tried this:

for (( c=1; c<5; c++ ))
do
  echo $c
  cat build.json | jq '.Stage${c}.Name'
done

And I got this error:

jq: error: syntax error, unexpected '$', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.Stage${c}.Name      
jq: 1 compile error

How do I do this properly?

peak
  • 105,803
  • 17
  • 152
  • 177
Jeel
  • 2,227
  • 5
  • 23
  • 38
  • 1
    I'm not sure if you really need a shell loop here. What is the actual task? – oguz ismail Dec 17 '20 at 09:31
  • For the record, you would need double quotes for this to work; but using `--arg` is a much better solution. See also https://stackoverflow.com/questions/6697753/difference-between-single-and-double-quotes-in-bash – tripleee Dec 17 '20 at 09:58

1 Answers1

0

Consider the following json file (./json.json):

{
    "data": {
        "stage1": {
            "name": 1
        },
        "stage2": {
            "name": 2
        },
        "stage3": {
            "name": 3
        },
        "stage4": {
            "name": 4
        },
        "stage5": {
            "name": 5
        }
    }
}

With this setup, you can use 's arg to parse your iterator:

#!/bin/bash
for (( i = 1; i <= 5; i++ )); do
    echo "i: $i"
    jq --arg i $i '.data.stage'$i'.name' < json.json
done

Producing the following output:

i: 1
1
i: 2
2
i: 3
3
i: 4
4
i: 5
5

passing arguments to jq filter

0stone0
  • 34,288
  • 4
  • 39
  • 64