I create bash script to parse json file and generate hosts. For that I use jq but I cannot get it work with variable domain_count
changing.
domain_count=0
jq -r .domains[] variables.json | while read domain; do
host="0.0.0.0 ${domain}"
echo $host;
# ((domain_count ))
done
echo $domain_count
It is still 0.
So that is because Process Substitution. I tried change it different ways. But non of it works.
while read domain
do
host="0.0.0.0 ${domain}"
echo $host;
((domain_count ))
done < <(jq -r .domains[] variables.json)
echo $domain_count
I got next error
generate.sh: line 20: syntax error near unexpected token `<'
generate.sh: line 20: `done < <(jq -r .domains[] variables.json)'
CodePudding user response:
Different steps of a pipeline behave like sub shells. Variables are inherited from the parent, but changes do not propagate back to the parent. You have to make your echo statement part of this step in the pipeline:
domain_count=0
jq -r '.domains[]' variables.json | {
while read -r domain; do
host="0.0.0.0 ${domain}"
echo "$host";
domain_count $((domain_count ))
done
echo $domain_count
}
But if all you want to do is count the number of domains/hosts, that can be done with jq directly:
domain_count=$(jq '.domains|length' variables.json)
And to output all domains formatted as hosts:
jq -r '.domains[] | "0.0.0.0 \(.)"' variables.json
Summarized, without losing functionality, your script can be shortened to:
jq -r '.domains[] | "0.0.0.0 \(.)"' variables.json
domain_count=$(jq '.domains|length' variables.json)