Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/65892044/bash-parse-environment-variables-in-bash-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...