A simple environment-to-file script. Match-and-replace values of key-value pairs in a file directly from your environment. Can be used for example in CI pipelines to generate .env files from their example equivalents.
The script goes through every key in a given key-value file. If a key has a value in the environment, the script replaces its value with the one from the environment. You can also provide a prefix to help keeping your variables separate.
sh dotenv-filler.sh FILE [VAR_PREFIX]
Parameters:
FILEThe key-value file to apply changes toVAR_PREFIX- Look for the variables with this prefix in the environment. This value is sanitized: All&*+,./:;@|~-characters are replaced with underscores (_) and then all non-alphanumeric characters (except_) are dropped. Finally, the value is changed to all uppercase for a usual env varaible format. This helps when one wants to use strings from other sources (for example git branch names) as prefix.
Let's take a file named .env with the following content:
FIRST_VARIABLE=
SECOND_VARIABLE=255
Running FIRST_VARIABLE=test sh dotenv-filler.sh .env will change the contents of the file to the following:
FIRST_VARIABLE=test
SECOND_VARIABLE=255
Running PRE_SECOND_VARIABLE=hello sh dotenv-filler.sh .env PRE will change the contents of the file to the following:
FIRST_VARIABLE=
SECOND_VARIABLE=hello