I am trying to save the output of the following command in a bash variable in a script. But no matter how hard i try, i am unable to escape the quotes correctly.
Here is the command whose output i want to save in a variable.
$ echo '[{"field":"fieldA","bucket":["a","b","c"]},{"field":"fieldB","bucket":["a","b","c","d"]}]' | jq -r '.[]|{field, bucketText: .bucket|join(", ")}|join(" found in bucket: ")'
fieldA found in bucket: a, b, c
fieldB found in bucket: a, b, c, d
And here is my attempt in my script file
#!/bin/bash
INPUT='[{"field":"fieldA","bucket":["a","b","c"]},{"field":"fieldB","bucket":["a","b","c","d"]}]'
OUTPUT_LINES="$(echo ${INPUT} | jq -r '.[]|{field, bucketText: .bucket|join(\", \")}|join(\" found in bucket: \")')"
printf "%s\n" "${OUTPUT_LINES}"
You may use this script:
#!/bin/bash
input='[{"field":"fieldA","bucket":["a","b","c"]},{"field":"fieldB","bucket":["a","b","c","d"]}]'
output="$(jq -r '.[]|{field, bucketText: .bucket|join(", ")}|join(" found in bucket: ")' <<< "$input")"
printf "%s\n" "$output"
Output:
fieldA found in bucket: a, b, c
fieldB found in bucket: a, b, c, d
Suggested changes:
jq
commands jq
command to avoid unnecessary sub-shell creation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.