Environment variables substitution for Go. see docs below
go get github.com/a8m/envsubst/cmd/envsubstThe envsubst binary is also available via Github releases
curl -L https://github.com/a8m/envsubst/releases/download/v1.1.0/envsubst-`uname -s`-`uname -m` -o envsubst
chmod +x envsubst
sudo mv envsubst /usr/local/binenvsubst < input.tmpl > output.text
echo 'welcome $HOME ${USER:=a8m}' | envsubst
envsubst -helpThere are two command line flags with which you can cause the substitution to stop with an error code, should the restriction associated with the flag not be met. This can be handy if you want to avoid creating e.g. configuration files with unset or empty parameters. The flags and their restrictions are:
| Flag | Meaning |
|---|---|
-no-unset |
fail if a variable is not set |
-no-empty |
fail if a variable is set but empty |
These flags can be combined to form tighter restrictions.
You can take a look on _example/main or see the example below.
package main
import (
"fmt"
"github.com/a8m/envsubst"
)
func main() {
input := "welcom $HOME"
str, err := envsubst.String(input)
// ...
buf, err := envsubst.Bytes([]byte(input))
// ...
buf, err := envsubst.ReadFile("filename")
}| Expression | Meaning |
|---|---|
${var} |
Value of var (same as $var) |
${var-$DEFAULT} |
If var not set, evaluate expression as $DEFAULT |
${var:-$DEFAULT} |
If var not set or is empty, evaluate expression as $DEFAULT |
${var=$DEFAULT} |
If var not set, evaluate expression as $DEFAULT |
${var:=$DEFAULT} |
If var not set or is empty, evaluate expression as $DEFAULT |
${var+$OTHER} |
If var set, evaluate expression as $OTHER, otherwise as empty string |
${var:+$OTHER} |
If var set, evaluate expression as $OTHER, otherwise as empty string |
$$var |
Escape expressions. Result will be $var. |
Most of the rows in this table were taken from here
os.ExpandEnv(s string) string- only supports$varand${var}notations
MIT