Skip to content

Instantly share code, notes, and snippets.

@mihow
Last active April 28, 2024 03:02
Show Gist options
  • Save mihow/9c7f559807069a03e302605691f85572 to your computer and use it in GitHub Desktop.
Save mihow/9c7f559807069a03e302605691f85572 to your computer and use it in GitHub Desktop.
Load environment variables from dotenv / .env file in Bash
if [ ! -f .env ]
then
export $(cat .env | xargs)
fi
@cihadturhan
Copy link

Thanks!
One-liner while running command a script (such as pnpm script)
I added parentheses not to pollute global environment vars. Not sure if it's needed though.

(export $(cat .env | xargs) && pnpm compile)

@rrakso
Copy link

rrakso commented Feb 28, 2024

source .env

works for me

wont work if you have # in your .env

@abhidp it seems, that it works well - even with comments in .env! :D (cc: @muthugit)

@MansourM
Copy link

this is the final version that im using, seems to work for all situations

read_env() {
  local filePath="${1:-.env}"

  if [ ! -f "$filePath" ]; then
    echo "missing ${filePath}"
    exit 1
  fi

  log "Reading $filePath"
  while read -r LINE; do
    # Remove leading and trailing whitespaces, and carriage return
    CLEANED_LINE=$(echo "$LINE" | awk '{$1=$1};1' | tr -d '\r')

    if [[ $CLEANED_LINE != '#'* ]] && [[ $CLEANED_LINE == *'='* ]]; then
      export "$CLEANED_LINE"
    fi
  done < "$filePath"
}

@benoit-cty
Copy link

Thanks @MansourM !

@xczdenis
Copy link

this is the final version that im using, seems to work for all situations

read_env() {
  local filePath="${1:-.env}"

  if [ ! -f "$filePath" ]; then
    echo "missing ${filePath}"
    exit 1
  fi

  log "Reading $filePath"
  while read -r LINE; do
    # Remove leading and trailing whitespaces, and carriage return
    CLEANED_LINE=$(echo "$LINE" | awk '{$1=$1};1' | tr -d '\r')

    if [[ $CLEANED_LINE != '#'* ]] && [[ $CLEANED_LINE == *'='* ]]; then
      export "$CLEANED_LINE"
    fi
  done < "$filePath"
}

Looks great, but it doesn't work if the .env file contains only 1 row (just one without br)

@MansourM
Copy link

MansourM commented Apr 27, 2024

Looks great, but it doesn't work if the .env file contains only 1 row (just one without br)

how do you use it?
you get any errors?
btw u need to comment or remove this line as you don't have the log function
log "Reading $filePath"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment