Skip to content

Commit

Permalink
Respect user-supplied quoting (#8)
Browse files Browse the repository at this point in the history
Currently it's impossible to have 'lazily' evaluated environment
variables like

```
  FOO='${BAR}'
```

where `${BAR}` is evaluated at runtime.

This is because we strip any quotes (single or double) and replace them
with double quotes, and then `${BAR}` is expanded.

Instead, we can check if the value is already quoted, and only supply
our own double quotes if it's not.
  • Loading branch information
iainlane authored Sep 2, 2022
1 parent a6380f4 commit 80f488c
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
13 changes: 8 additions & 5 deletions dotenv.sh
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,14 @@ export_envs() {
continue
fi

# Strip any existing quotes
temp="${temp%[\'\"]}";
temp="${temp#[\'\"]}";
# Add new double quotes for interpolation
value=$(eval echo "\"$temp\"");
# check if $temp doesn't start with with ' or ", and quote it if so
if [ "${temp%%[\"\']*}" = "${temp}" ]; then
temp="\"${temp}\""
fi

# We have already quoted if necessary, so we can safely eval it
# shellcheck disable=SC2086
value=$(eval echo ${temp});

eval export "$key='$value'";
echo "$key=$value" >> $GITHUB_ENV;
Expand Down
5 changes: 5 additions & 0 deletions tests/.env
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
TEST_UNQUOTED=a=1 b=2 c=3
# Comment 2
TEST_SINGLE_QUOTED='1 2 3 4'

# This is single-quoted, so it should be treated as a literal
TEST_SINGLE_QUOTE_NO_INTERPOLATE='${TEST}'

# Comment 3
TEST_DOUBLE_QUOTED="1 2 3 4"
# Comment 4
Expand All @@ -15,5 +19,6 @@ TEST_EXISTING="new-value"
TEST_DOTENV_OVERRIDES_DEFAULT="expected"
# Test special characters are escaped
TEST_SPECIAL_CHARACTER=special(character

# Test that the last variable is parsed despite no trailing new line
TEST_NO_NEWLINE="still there"
3 changes: 3 additions & 0 deletions tests/dotenv-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ main() {
echo "Testing blank line parsing: ok" # i.e. didn't crash
assert_equal "$TEST_UNQUOTED" 'a=1 b=2 c=3' 'Testing unquoted'
assert_equal "$TEST_SINGLE_QUOTED" '1 2 3 4' 'Testing single quoted'
# We want to test it expands to this literal value
# shellcheck disable=SC2016
assert_equal "$TEST_SINGLE_QUOTE_NO_INTERPOLATE" '${TEST}' 'Testing single-quoted variables arent interpolated'
assert_equal "$TEST_DOUBLE_QUOTED" '1 2 3 4' 'Testing double quoted'
assert_equal "$TEST_INTERPOLATION" 'a=1 b=2 c=3 d=4' 'Testing interpolation'
assert_equal "$TEST_EXISTING" 'new-value' 'Testing overwrite of existing variables'
Expand Down

0 comments on commit 80f488c

Please sign in to comment.