Skip to content

Instantly share code, notes, and snippets.

@RA80533
Created June 11, 2020 04:05
Show Gist options
  • Save RA80533/62427948b629b3f906b65fb6ccd73b8b to your computer and use it in GitHub Desktop.
Save RA80533/62427948b629b3f906b65fb6ccd73b8b to your computer and use it in GitHub Desktop.
#! /usr/bin/env bash
# Populate the current shell with environment variables sourced from the .env
# file in the current working directory.
#
# This script is designed to take advantage of how Yarn assigns the INIT_CWD
# environment variable based on where a package.json script is called from in a
# workspace-enabled project.
#
# EXAMPLE USAGE:
# "scripts": {
# "build": "yarn workspaces run build",
# "clean": "yarn workspaces run clean",
# "start": "./opt/with-env.sh node bin/index.js"
# }
load_env () {
# Read the current environment variables
eval "$(export -p)"
set -o allexport
source "${1:0}" 2> /dev/null
set +o allexport
}
# The specific file to source depends on if Yarn has set INIT_CWD
load_env "${INIT_CWD:-${PWD}}/.env"
# Execute any commands passed to the script
eval "${@:1}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment