I am struggling to understand what the cause of the following bug is and how I can fix it.
I have this code:
set_filters() {
json=$1
filters='"Name=instance-state-name,Values=running,stopped"'
echo $json | jq -r '. | keys[]' | \
while read tag ; do
value=$(echo "$json" | jq -r ".[\"$tag\"]")
filters="$filters \"Name=tag:${tag},Values=${value}\""
done
echo $filters
}
set_filters '{"Name": "*FOO*", "Cost Center": "XX111"}'
The output I am expecting:
"Name=instance-state-name,Values=running,stopped" "Name=tag:Cost Center,Values=XX111" "Name=tag:Name,Values=*FOO*"
The output I am getting:
"Name=instance-state-name,Values=running,stopped"
If I insert echo statements to assist with debugging:
set_filters() {
json=$1
filters='"Name=instance-state-name,Values=running,stopped"'
echo $json | jq -r '. | keys[]' | \
while read tag ; do
value=$(echo "$json" | jq -r ".[\"$tag\"]")
filters="$filters \"Name=tag:${tag},Values=${value}\""
echo "FILTERS INSIDE LOOP: $filters"
done
echo "FILTERS OUTSIDE LOOP: $filters"
}
The output I then get is:
FILTERS INSIDE LOOP: "Name=instance-state-name,Values=running,stopped" "Name=tag:Cost Center,Values=XX111"
FILTERS INSIDE LOOP: "Name=instance-state-name,Values=running,stopped" "Name=tag:Cost Center,Values=XX111" "Name=tag:Name,Values=*FOO*"
FILTERS OUTSIDE LOOP: "Name=instance-state-name,Values=running,stopped"
I can't explain the behaviour. In a language other than Bash I would assume a variable scope issue for the variable $filters, but I thought the scope would basically be global.
I am using JQ version 1.3 and Bash version 4.1.2 on Red Hat Enterprise Linux 6.8.
jq, while still demonstrating this strange behavior.jqquestion, since you can probably dispense with all of the wrappers aroundjqand use a singlejqcommand instead: consider the output ofecho "$1" | jq '.keys as $k | "Name=tag:\($k),Values=\(.[$k])".