Skip to content

Instantly share code, notes, and snippets.

@joshgav
Last active August 10, 2020 19:49
Show Gist options
  • Save joshgav/9e1d8c422f1f100ceacc578f3c13d842 to your computer and use it in GitHub Desktop.
Save joshgav/9e1d8c422f1f100ceacc578f3c13d842 to your computer and use it in GitHub Desktop.
A bash equivalent of gettext's envsubst executable.
# envsubst invokes all shell substitutions in a file
# use by first sourcing this file, e.g. `source envsubst.sh` or `. envsubst.sh`,
# and then invoking `envsubst` on STDIN or a specific file
# it should only be invoked on trusted or scrubbed files to avoid injection attacks
function envsubst {
local infile=${1}
if [[ "${SUPPRESS_ENVSUBST_WARNING}" != "1" ]]; then
>&2 echo "[WARNING] the envsubst function should only be used on trusted files because it is vulnerable to injection attacks"
fi
# ${infile:--} means:
# 1. if infile is set use its value
# 2. if infile is unset or null (":-"), read from stdin ("-")
# sed replaces '"' with '\"' so that it's retained by echo
# the part within `$()` is executed first, then eval is called
eval "echo \"$(cat ${infile:--} | sed 's/\"/\\"/g')\""
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment