I'm trying to create a JSON in BASH where one of the fields is based on the result of an earlier commandBIN=$(cat next_entry)OUTDIR=/tmp/cpupower/${BIN}echo $OUTDIRJSON=''{hostname: localhost, outdir: ${OUTDIR}, port: 20400, size: 100000}''echo $JSONThe above script when executed, returns:/tmp/cpupower/0, port: 20400, size: 100000}': /tmp/cpupower/0How can I properly substitute variables inside these multi-quoted strings?
Bash variable substitution in a JSON string
bash;variable substitution;json
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