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