0

Running into an issue that is likely simple for people that know how. I am writing an .sh script that reads in a file that has variable names in it. I am trying to use the file following this with the values of the variables in place for the names in the file.

My Attempted .sh Script:

HELLOVAR = "hello"
cat infilename.json > outfilename.json

I then attempt to use outfilename.json, but it has not changed from the original infile.

File In Example:

I would like this to be ${HELLOVAR}.

File Out Wanted:

I would like this to be hello.
2
  • 1
    Surely you get an error of the form HELLOVAR: command not found. If not, show us your actual code. Commented Dec 6, 2022 at 16:26
  • Do you need to worry about HELLOVAR='hello "cruel" world' (which, to be included in a JSON string, would need to be changed to hello \"cruel\" world), or is your data pre-escaped to be JSON-safe? (If it's the former, you should use jq instead of envsubst; it's perfectly capable of looking up environment variables). Commented Dec 6, 2022 at 16:48

1 Answer 1

1

You probably just want:

HELLOVAR=hello envsubst < infilename.json > outfilename.json

envsubst reads its input stream looking for simple variable expressions (eg, it will substitute $FOO and ${FOO}, but will not perform the expected substitution on expressions like ${FOO-bar}) and expands them according to the current setting in the environment. HELLOVAR=hello envsubst invokes envsubst with HELLOVAR set to hello in its environment.

Sign up to request clarification or add additional context in comments.

4 Comments

This is problematic if any of the values require escaping. I'd argue that this would be better resolved by the answers to Replacing variables in a JSON template using jq
(maybe not that one; I know we have a Q&A entry somewhere with jq code that searches a document's strings for ${varname} references and looks up the named variables in env)
Would there be a way to achieve this without actual saving the output file. Instead just have it be usable in the script itself?
@toren It depends on what you mean. There are a lot of options. You could pipe the output of envsubst into some command block, or you could save its output to a variable, or you could run envsubst inside a heredoc, or any number of other methods for making the data available to the script. But storing it on the filesystem is a pretty good method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.