使用 bash 解析 .env 文件并将其注入命令行

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

我正在使用 kubernetes 并尝试调用以下命令:
kubectl set env deployment/server A=a B=b ...etc 我的环境变量位于 .env 文件中,每个值可以包含空格、非转义字符、注释、空行等:

## 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>&

我正在尝试解析 .env 文件,以便将其集成到命令中:

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

已尝试 grep -v '^#' .env | xargs,但它不适用于需要转义或引号的字符。我的 bash 能力目前还不是最强的。知道如何解决这个问题吗?

cat .env | grep -v '^#\|^$' | xargs -0 echo | tr '\n' ' '

这会在一行中打印所有内容: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>&

我不确定你是否需要保留 VAR= 或者你是否也想摆脱它(最后输入 sedawk 然后用你需要的任何东西替换它)