Using bash to parse .env file and inject it to command line

2/13/2019

I am using kubernetes and trying to call the following command:
kubectl set env deployment/server A=a B=b ...etc My env variables are located in .env file, and each value can contain spaces, non-escaped chars, comments, empty lines and so on:

## Common variables
NODE_ENV=production


## Server variables
SERVER_PORT=8009
CORS_ORIGIN=https://www.example.io,http://www.example.io,http://localhost:3000
SESSION_SECRET=/qm%7HLw"pk(8@"pja#I9CbN#2Lg[%d>5{CDA_9g|ZvZmuZ$]=';EhA#g+C;1>&

I am trying to parse the .env file so that I can integrate it in the command:

kubectl set env deployment/server $(do magic with .env file to extract the escaped variables)

Tried grep -v '^#' .env | xargs but it doesn't work with characters that need escaping or quotes. My bash abilities are not the strongest right now. Any idea how to solve this?

-- Naor
bash
environment-variables
kubectl
kubernetes
unix

1 Answer

2/13/2019
cat .env | grep -v '^#\|^
#x27;
| xargs -0 echo | tr '\n' ' '

This would print everything in one line: NODE_ENV=production SERVER_PORT=8009 CORS_ORIGIN=https://www.example.io,http://www.example.io,http://localhost:3000 SESSION_SECRET=/qm%7HLw"pk(8@"pja#I9CbN#2Lg[%d>5{CDA_9g|ZvZmuZ$]=';EhA#g+C;1>&

I am not sure if you need to keep the VAR= or if you also would like to get rid of that (pipe into sed or awk in the end then and replace it with whatever you need)

-- Alberti Buonarroti
Source: StackOverflow