Replace shell variables in a file with their actual values

Solution for Replace shell variables in a file with their actual values
is Given Below:

Is it possible to insert variable defined in shell file into string that was read from another file? (In this sample it’s just 1 variable to insert but I’ll need many)

E.g. have file example.txt

Hello $WORLD

And script file

FILE_STRING=$(cat example.txt)

Running this script I have

Hello $WORLD

But I want to have

Hello world!

You could use envsubst from GNU gettext-runtime to dynamically substitute variable values from files.

WORLD=world! envsubst < example.txt

or even more succinctly, refer variables by name that you want to substitute,

WORLD=world! envsubst '$WORLD' < example.txt

and store the result in a variable using command substitution $(..)

FILE_STRING="$(WORLD=world! envsubst '$WORLD' < example.txt)"

As a better practice, always use lower case variable names for referring user defined variables, so that they are not misinterpreted as environment variables.

I guess the easiest option is to use “eval” before the echo.

For script file:

FILE_STRING=$(cat example.txt)
eval echo $FILE_STRING

If you want to learn more about eval, you can take a look here: