2

How can I use curl and/or bash to post a file, substituting env variables.

Lets say I have test.json like so (which I can edit the format of):

{
  "name": "'"$NAME_VAR"'"
}

how can I post this file via curl, while substituting any env variable?

Example curl of posting a test.json file without substitutions:

curl -X POST -H 'Content-Type: application/json' --data-binary @test.json http://test-server/some/path
  • Does this answer your question? [Convert log files to base64 and upload it using Curl to Github](https://stackoverflow.com/questions/69448044/convert-log-files-to-base64-and-upload-it-using-curl-to-github) – Léa Gris Oct 13 '21 at 05:28
  • 1
    I'm not sure I follow exactly what you're trying to do but maybe [this](https://stackoverflow.com/a/64038384/12195738) will help. – Rfroes87 Oct 13 '21 at 16:31
  • Thanks, This is what I ended up using: `envsubst "\`printf '${%s} ' $(sh -c "env|cut -d'=' -f1")\`" < test.json > test2.json` – Thomas Freiling Oct 14 '21 at 17:34

1 Answers1

1

This seems like an XY Problem. Even if it isn't the question is underspecified. Does the solution have to support arbitrary var names or are they known apriori? Can the values contain quote marks that need to be properly escaped when interpolated into the JSON text? Why does the JSON text contain this unusual quoting:

"name": "'"$NAME_VAR"'"

If that can be changed to a single double-quote on each side of the env var name, and the env var value doesn't contain quotes, then the envsubst command is the simplest solution.

Kurtis Rader
  • 6,734
  • 13
  • 20
  • Thanks, I ended up using envsubst. Specifically, I used this in order to replace any/only defined env variables: ` envsubst "\`printf '${%s} ' $(sh -c "env|cut -d'=' -f1")\`" < test.json > test2.json ` Regarding: ` Does the solution have to support arbitrary var names or are they known apriori? ` Yes, as specified (`how can I post this file via curl, while substituting any env variable?`) ` Can the values contain quote marks that need to be properly escaped when interpolated into the JSON text ` Yes, as specified (`which I can edit the format of`) – Thomas Freiling Oct 14 '21 at 17:28