Ever want to use .env file config directly in Makefile? I found it not as easy as it sounds. I found this shell command on the web that read and export a simple .env file (also strip away comments).
1 | export $(cat .env | grep -v ^# | xargs) |
Consider the following Makefile, “docker-compose …” can be whatever command you use to compile something or run something.
1 2 3 4 | deploy: docker-compose -f docker-compose.yml up -d .PHONY: deploy |
To export the .env while running the command in “deploy” task , you have to do this:
1 2 3 4 5 | deploy: export $$(cat .env | grep -v ^\# | xargs) && \ docker-compose -f docker-compose.yml up -d .PHONY: deploy |
this key is to use $$ instead of $ to use shell variable, and you need to escape the character # with a backlash \
Shell Tools
If you need to do this a lot, I have invented a little shell tools to use dotenv in anything (really?). Please checkout my git repo dotenv-shell here. Have fun and send me pull requests anytime!
for example, you can simply the above makefile into:
1 2 3 4 | deploy: dotenv docker-compose -f docker-compose.yml up -d .PHONY: deploy |
Hope you find this useful!