Can Envsubst Be Used to Replace Environment Variables in a Given Variable, Not File?

I know that I can use envsubst command to replace environment variables inside a file and write it to an output file:

envsubst < input.txt > output.txt

However, now I only have a variable and it's not a file. But I still need to replace any environment variable inside it.

export original_text="Hello $name, please come here $date"
# I want to be able to replace $name and $date, in the RAM and not on disk and files
export $name="John"
export $date="tomorrow"
output=$(envsubst < $original_text) # this is a pseudo-command
echo $output
# prints => Hello John, please come here tomorrow

Is it possible? How can do this?

1 Answer

Yes, you can use a here-string: <<< "$variable"

Your original_text must be single quoted, otherwise the variables will be replaced on creating original_text.

$ original_text='Hello $name, please come here $date'
$ export name="John"
$ export date="tomorrow"
$ envsubst <<< "$original_text"
Hello John, please come here tomorrow

Of course, you can save it in a variable like you'd always do:

output=$(envsubst <<< "$original_text")

You can also pipe to envsubst, e.g.:

$ printf '%s\n' "$var" | envsubst
Hello John, please come here tomorrow
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest