Sometimes in a GitHub Actions workflow, we want to inject environment variables from a .env.<environment-name>
file.
For example, .env.test
:
# .env.test
FOO=bar
BAZ=1
In order to do that, it’s quite tempting to use a third-party action (eg. action-dotenv-to-setenv
) to do this, like so:
- uses: c-py/action-dotenv-to-setenv@v2
with:
env-file: .env.test
- run: echo $FOO # Will output `bar`
But now that GitHub Actions supports appending new environment variables to the $GITHUB_ENV
file, I realized it would be pretty simple to replace this action with a one-liner script:
- run: grep -v '^\(#.*\|\s\?\)$' .env.test >> $GITHUB_ENV
- run: echo $FOO # Will output `bar`
We use a regular expression (❤️) to filter out (grep -v
) empty and commented out lines (^(#.*|\s?)$
) from .env.test
, then we pipe the output to $GITHUB_ENV
.