Skip to content

Instantly share code, notes, and snippets.

@mikew
Last active October 9, 2015 03:50
Show Gist options
  • Save mikew/0cc41914e8292f4110fb to your computer and use it in GitHub Desktop.
Save mikew/0cc41914e8292f4110fb to your computer and use it in GitHub Desktop.
replace-all-env-vars bash function

Usage

cat /file | replace-all-env-vars > /file
# Or:
replace-all-env-vars /file > /file
function replace-all-env-vars () {
  # Work with either `cat /file | replace-all-env-vars` and
  # `replace-all-env-vars /file`
  [ $# -ge 1 -a -f "$1" ] && input="$1" || input="-"
  local contents=$(cat $input)

  # Loop through each environment variable name
  for v in $(env | cut -d '=' -f1); do
    # Only look for things like `__ENV_PATH__`
    local needle="__ENV_${v}__"
    if [[ "${contents}" =~ "${needle}" ]]; then
      # Replace all instances of needle with the value of `$v`
      contents="${contents//$needle/${!v}}"
    fi
  done

  echo "${contents}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment