Skip to content

Instantly share code, notes, and snippets.

@vincent-zurczak
Created February 29, 2024 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vincent-zurczak/77fa9d1447b2e8ae37231abd2c7ff49a to your computer and use it in GitHub Desktop.
Save vincent-zurczak/77fa9d1447b2e8ae37231abd2c7ff49a to your computer and use it in GitHub Desktop.
Replace values by env vars (envsubst opposite)
#!/bin/bash
# 1. Let's assume we have a 'secrets.env' file that lists variables and their values.
#
# ENV_1=VALUE_1
# ENV_2=VALUE_2
# ENV_3=VALUE_3
#
# And we have a file that contains hard-coded values, e.g.
# my_content is VALUE_3
#
# We want this script to transform it into...
# my_content is ${ENV_3}
#
# Somehow, this is almost the opposite of the envsubst command.
# "envsubst" substitutes placeholders by env values.
# Here, we replace env values by placeholders.
# With special characters support, etc.
SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
while IFS= read -r line
do
VAR=$(echo $line | cut -d "=" -f 1)
VALUE=$(echo $line | cut -d "=" -f 2)
echo $VALUE
# Escape special characters for sed
CLEANED_VALUE=$(sed -e 's/[&\\/]/\\&/g; s/$/\\/' -e '$s/\\$//' <<<"$VALUE")
# Replace values by a reference to their env variable
sed -i "s@$CLEANED_VALUE@\${$VAR}@g" my_file_to_update
done < "$SCRIPT_DIR/secrets.env"
@vincent-zurczak
Copy link
Author

Obviously, this would require some automated tests to verify all the cases.
I tested values with special chars like ? and &, but not with @. This gist is more a sticky note I created at the end of a busy day: it may be updated later.

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