|
| 1 | +#!/bin/sh |
| 2 | +# Filename: dotenv |
| 3 | +# Purpose: import environment variables from .env file and make available to other commands |
| 4 | +# Authors: Jason Leung ([email protected]), multiple contributors (https://github.com/madcoda/dotenv-shell/graphs/contributors) |
| 5 | +# Bug-Reports: see https://github.com/madcoda/dotenv-shell/issues |
| 6 | +# License: This file is licensed under the MIT License (MIT). |
| 7 | +################################################################################ |
| 8 | + |
| 9 | + |
| 10 | +set -e |
| 11 | + |
| 12 | +log_verbose() { |
| 13 | + if [ "$VERBOSE" = 1 ]; then |
| 14 | + echo "[dotenv.sh] $1" >&2 |
| 15 | + fi |
| 16 | +} |
| 17 | + |
| 18 | +is_set() { |
| 19 | + eval val=\""\$$1"\" |
| 20 | + if [ -z "$(eval "echo \$$1")" ]; then |
| 21 | + return 1 |
| 22 | + else |
| 23 | + return 0 |
| 24 | + fi |
| 25 | +} |
| 26 | + |
| 27 | +is_comment() { |
| 28 | + case "$1" in |
| 29 | + \#*) |
| 30 | + log_verbose "Skip: $1" |
| 31 | + return 0 |
| 32 | + ;; |
| 33 | + esac |
| 34 | + return 1 |
| 35 | +} |
| 36 | + |
| 37 | +is_blank() { |
| 38 | + case "$1" in |
| 39 | + '') |
| 40 | + log_verbose "Skip: $1" |
| 41 | + return 0 |
| 42 | + ;; |
| 43 | + esac |
| 44 | + return 1 |
| 45 | +} |
| 46 | + |
| 47 | +export_envs() { |
| 48 | + while IFS='=' read -r key temp || [ -n "$key" ]; do |
| 49 | + if is_comment "$key"; then |
| 50 | + continue |
| 51 | + fi |
| 52 | + |
| 53 | + if is_blank "$key"; then |
| 54 | + continue |
| 55 | + fi |
| 56 | + |
| 57 | + value=$(eval echo "$temp") |
| 58 | + eval export "$key='$value'"; |
| 59 | + done < $1 |
| 60 | +} |
| 61 | + |
| 62 | +# inject any defaults into the shell |
| 63 | +if is_set "DOTENV_DEFAULT"; then |
| 64 | + log_verbose "Setting defaults via $DOTENV_DEFAULT" |
| 65 | + if [ -f "$DOTENV_DEFAULT" ]; then |
| 66 | + export_envs "$DOTENV_DEFAULT" |
| 67 | + else |
| 68 | + echo '$DOTENV_DEFAULT file not found' |
| 69 | + fi |
| 70 | +fi |
| 71 | + |
| 72 | +if is_set "DOTENV_FILE"; then |
| 73 | + log_verbose "Reading from $DOTENV_FILE" |
| 74 | +else |
| 75 | + DOTENV_FILE=".env" |
| 76 | +fi |
| 77 | + |
| 78 | +# inject .env configs into the shell |
| 79 | +if [ -f "$DOTENV_FILE" ]; then |
| 80 | + export_envs "$DOTENV_FILE" |
| 81 | +else |
| 82 | + echo "$DOTENV_FILE file not found" |
| 83 | +fi |
| 84 | + |
| 85 | + |
| 86 | +# then run whatever commands you like |
| 87 | +if [ $# -gt 0 ]; then |
| 88 | + exec "$@" |
| 89 | +fi |
0 commit comments