<!DOCTYPE html>
<html>
<head>
<title>Build a JSON string with Bash variables</title>
</head>
<body>
<p>First, don't use ALL_CAPS_VARNAMES: it's too easy to accidentally overwrite a crucial shell variable (like PATH).</p>
<p>Mixing single and double quotes in shell strings can be a hassle. In this case, I'd use printf
:</p>
<pre>bucket_name=testbucket
object_name=testworkflow-2.0.1.jar
target_location=/opt/test/testworkflow-2.0.1.jar
template='{"bucketname":"%s","objectname":"%s","targetlocation":"%s"}'
json_string=$(printf "$template" "$BUCKET_NAME" "$OBJECT_NAME" "$TARGET_LOCATION")
echo "$json_string"
</pre>
<p>For homework, read this page carefully: <a href="https://unix.stackexchange.com/q/171346/4667" target="_blank">Security implications of forgetting to quote a variable in bash/POSIX shells</a></p>
<hr>
<p>A note on creating JSON with string concatenation: there are edge cases. For example, if any of your strings contain double quotes, you can broken JSON:</p>
<pre>$ bucket_name='a "string with quotes"'
$ printf '{"bucket":"%s"}\n' "$bucket_name"
{"bucket":"a "string with quotes""}
</pre>
<p>Do do this more safely with bash, we need to escape that string's double quotes:</p>
<pre>$ printf '{"bucket":"%s"}\n' "${bucket_name//\"/\\\"}"
{"bucket":"a \"string with quotes\""}
</pre>
Build a JSON string with Bash variables
```html