4

I need, using bash script, create json file with some variables within.

For this purposes, I have a bash file, who creates json template file using cat:

cat <<'EOF' > template.json
{
"ip_range" : "$snmp_ip1", 
"types" : [ "snmp" ],
"description" : "$snmp_cred1",
"snmp.version": "v2c",
"snmp.port" : 161,
"snmp.community" : "$snmp_cred1",
"snmp.retries" : 3,
"snmp.timeout" : 2
}
EOF

Unfortunately, cat does not expand variables into values. So, then I need to insert some variables into template using jq and create some new file with expanded variables. I tried to use jq for this with following code:

jq \
--arg snmp_ip1 "$snmp_ip" \
--arg snmp_cred1 "$snmp_cred" \
'.["snmp_ip1"]=$snmp_ip1 | .["snmp_cred"]=$snmp_cred1' \
<$DIR/template.json >$DIR/cred.json

Unfortunatelly, it just inserts new strings with variables, but not expands variables in template:

{
"snmp_cred": "fortinet/fortigate/1.3.6.1.4.1.12356.101.1.37000_fortigate3700d/10.82.112.21@public",
"snmp_ip1": "10.82.112.21",
"ip_range": "$snmp_ip1",
"types": [
"snmp"
],
"description": "$snmp_cred1",
"snmp.version": "v2c",
"snmp.port": 161,
"snmp.community": "snmp_cred1",
"snmp.retries": 3,
"snmp.timeout": 2
}

Can you hint me, how to rewrite script (or, maybe use another approach) to create json files with this output:

{
"ip_range": "10.82.112.21",
"types": [ "snmp" ],
"description": "fortinet/fortigate/1.3.6.1.4.1.12356.101.1.37000_fortigate3700d/10.82.112.21@public",
"snmp.version": "v2c",
"snmp.port": 161,
"snmp.community": "fortinet/fortigate/1.3.6.1.4.1.12356.101.1.37000_fortigate3700d/10.82.112.21@public",
"snmp.retries": 3,
"snmp.timeout": 2
}

1 Answer 1

3

Remove the quotes around your delimieter EOF as this causes cat to not expand variables.

Sign up to request clarification or add additional context in comments.

3 Comments

When I changed it to: cat <<EOF > template.json - it just delete variables from template. For example - "ip_range" : "",
What does echo $snmp_ip1 immediately before the cat return?
Oh, my fault. I've just entered wrong variable names in cat section. Thanks, your advice works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.