The issue is that the shell does not expand variables inside single-quoted strings. A minor other thing is that your NAME
variable actually happens to be an array due to the way you assign the value to it (NAME=(...)
). You also use your OUTPUT
variable unquoted (which would split its contents on white-spaces and apply filename globbing to all the generated words) and with echo
(which may, under some circumstances, modify the data that it's outputting).
Consider adopting safer ways of creating JSON documents. It is not always possible to inject a shell string into a JSON document. In this particular case, it ought to be fairly safe, but you generally want to use a tool that knows how to handle characters like quotes and newlines properly.
Using jo
to create the JSON document:
#!/bin/bash
printf -v name 'host-%s' "$(( 1 + (RANDOM % 10) ))"
jo hostname="$name" plan='baremetal_0' operating_system='coreos_stable'
Using jq
to do the same thing:
#!/bin/bash
printf -v name 'host-%s' "$(( 1 + (RANDOM % 10) ))"
jq -n -c --arg name "$name"
'{ "hostname": $name, "plan": "baremetal_0", "operating_system": "coeros_stable" }'
Note that in both these cases,
- The string
$name
is properly JSON encoded. This matters since it's possible that one at some later point decides that $name
should be some other random string that may need encoding.
- The output from
jo
/jq
is not saved in a shell variable. This is not needed since we're just interested in outputting the generated JSON document.
$NAME
may contain characters that needs to be encoded before included in the JSON document. Also, this solution solves the issue by leaving the$NAME
expansion totally unquoted, which is generally a bad idea. – Kusalananda Jul 10 '21 at 22:01$NAME
is only going to contain digits. – Guido Jul 12 '21 at 00:16