0

I'm trying to get all results of jq query in a array in bash, but it gives me all results in the first array element. Could you help me? I would like to having every result in one array element

bash-4.2$ try=$(tm run jobs:status::get -s "tm=serverA&work=*&status=Failed" | $PATH_API/jq -r '.statuses[].name // empty')
bash-4.2$ echo $try
job_B job_C
bash-4.2$ echo "${#try[@]}"
1
bash-4.2$
defekas17
  • 155
  • 1
  • 9
  • `variable=$(command)` creates a **string** variable, not an array. – Charles Duffy Nov 16 '20 at 14:01
  • ...btw, using `declare -p try` instead of `echo $try` will provide a more unambiguous readout of the variable's value. With your current value it should emit `declare -- try="job_B job_C"`; with a real array it would be `declare -a try=( [0]=job_B [1]=job_C )` – Charles Duffy Nov 16 '20 at 14:04

1 Answers1

0

If the status names are sufficiently uncomplicated, you could add an extra pair of parentheses:

try=($(tm run ....))

(Consider also invoking jq without the -r option.)

Otherwise, you could consider using readarray, or other techniques for initializing bash arrays.

peak
  • 105,803
  • 17
  • 152
  • 177
  • Please don't advise that -- see BashPitfalls #50. – Charles Duffy Nov 16 '20 at 14:00
  • I thought the proviso would be warning enough... – peak Nov 16 '20 at 14:02
  • Better to show a good-practice approach rather than a known antipattern. As an example that works even with the older bash releases Apple ships: `read -r -d '' -a try < <(tm run ... && printf '\0')` -- even has a compelling advantage over the modern `readarray` approach insofar as it passes a nonzero exit status through (by emitting the trailing NUL, which causes `read` to return nonzero if the pipeline returned nonzero). – Charles Duffy Nov 16 '20 at 14:05