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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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