Score:0

Can envsubst be used to replace environment variables in a given variable, not file?

cn flag

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?

Score:2
in flag

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
Saeed Neamati avatar
cn flag
Awesome, how can I get the result in a variable instead of the command line?
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.