Bash variable substitution in a JSON string

bashjsonvariable substitution

I'm trying to create a JSON in BASH where one of the fields is based on the result of an earlier command

BIN=$(cat next_entry)
OUTDIR="/tmp/cpupower/${BIN}"
echo $OUTDIR
JSON="'"'{"hostname": "localhost", "outdir": "${OUTDIR}", "port": 20400, "size": 100000}'"'"
echo $JSON

The above script when executed, returns:

/tmp/cpupower/0
, port: 20400, size: 100000}': /tmp/cpupower/0

How can I properly substitute variables inside these multi-quoted strings?

Best Answer

JSON=\''{"hostname": "localhost", "outdir": "'"$OUTDIR"'", "port": 20400, "size": 100000}'\'

That is get out of the single quotes for the expansion of $OUTDIR. We did put that expansion inside double-quotes for good measure even though for a scalar variable assignment it's not strictly necessary.

When you're passing the $JSON variable to echo, quotes are necessary though to disable the split+glob operator. It's also best to avoid echo for arbitrary data:

printf '%s\n' "$JSON"