简体   繁体   中英

Bash - Parse environment variables in bash function

I have a bash function that retrieves environment variables from a .env file.

In my .env file I have the following variables

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

In my bash script I have my env 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 .

Expected result: luis/application:latest

Current result: ${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.

The file looks like it wants to keep shell-ish syntax. If so, just source it:

. ./.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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