简体   繁体   English

Bash - 解析 bash function 中的环境变量

[英]Bash - Parse environment variables in bash function

I have a bash function that retrieves environment variables from a .env file.我有一个 bash function 从.env文件中检索环境变量。

In my .env file I have the following variables在我的.env文件中,我有以下变量

USER=luis
IMAGE_NAME=application
IMAGE_VERSION=latest
IMAGE_TAG=${USER}/${IMAGE_NAME}:${IMAGE_VERSION}

In my bash script I have my env function在我的 bash 脚本中,我有我的环境 function

function dotenv::get() {
  variable=$(grep ^"${1}"= "$(pwd)/.env" | xargs)
  IFS="=" read -ra variable <<< "${variable}"

  echo "${variable[1]}"
}

When I execute dotenv::get IMAGE_TAG .当我执行dotenv::get IMAGE_TAG时。

Expected result: luis/application:latest预期结果: luis/application:latest

Current result: ${USER}/${IMAGE_NAME}:${IMAGE_VERSION}当前结果: ${USER}/${IMAGE_NAME}:${IMAGE_VERSION}

I'm aware my function is incomplete, however I'm not sure what are the next steps to achieve my objective.我知道我的 function 不完整,但是我不确定实现我的目标的下一步是什么。

The file looks like it wants to keep shell-ish syntax.该文件看起来想要保留 shell-ish 语法。 If so, just source it:如果是这样,只需source它:

. ./.env
echo "$IMAGE_TAG"

dotenv::get() { 
    . ./.env;
    echo "${!1}"
}

If this is not your intention, then implement a whole parser of variables from a file with a ${...} variable substitution of already set variables.如果这不是您的意图,则使用${...}变量替换已设置变量的文件实现整个变量解析器。

You are still missing two things: interpreting your variable assignments, and interpreting the content of the variable you query:您仍然缺少两件事:解释您的变量分配,并解释您查询的变量的内容:

. $(pwd)/.env  # source the environment file so that variables are assigned

function dotenv::get() {
  variable=$(grep ^"${1}"= "$(pwd)/.env" | xargs)
  IFS="=" read -ra variable <<< "${variable}"

  eval X=${variable[1]}  # interpret the expression containing variables
  echo $X
}

dotenv::get IMAGE_TAG

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM