Conghao97's picture tcftrees's picture
ProgramGen release
d086025
|
Raw History Blame Contribute Delete
3.05 kB

envsubst — Usage Documentation

Environment variables substitution tool (Go implementation of shell-style variable expansion).

Installation

From prebuilt binaries

Latest stable envsubst binaries for 64-bit Linux, macOS, and Windows are available via the GitHub releases page.

Linux / macOS:

curl -L https://github.com/a8m/envsubst/releases/download/v1.2.0/envsubst-`uname -s`-`uname -m` -o envsubst
chmod +x envsubst
sudo mv envsubst /usr/local/bin

Windows:

curl -L https://github.com/a8m/envsubst/releases/download/v1.2.0/envsubst.exe

With Go

go get github.com/a8m/envsubst/cmd/envsubst

CLI usage

envsubst < input.tmpl > output.text
echo 'welcome $HOME ${USER:=a8m}' | envsubst
envsubst -help

If no input file is given, input is read from stdin. If no output file is given, output is written to stdout.

Command-line flags

Option Meaning Type Default
-i input file string | stdin stdin
-o output file string | stdout stdout
-no-digit do not replace variables starting with a digit, e.g. $1 and ${1} flag false
-no-unset fail if a variable is not set flag false
-no-empty fail if a variable is set but empty flag false
-fail-fast fail on first error instead of collecting all errors; ignored unless -no-empty or -no-unset is set flag false

These flags can be combined to form tighter restrictions (e.g. to avoid creating configuration files with unset or empty parameters). Setting -fail-fast together with -no-unset and/or -no-empty gives a faster feedback loop on large inputs; otherwise a list of all errors is returned.

Supported expressions

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: result will be $var

Note: os.ExpandEnv only supports the $var and ${var} notations; this tool supports the full set above.

Programmatic (Go API) usage

package main

import (
    "fmt"
    "github.com/a8m/envsubst"
)

func main() {
    input := "welcome $HOME"
    str, err := envsubst.String(input)
    // ...
    buf, err := envsubst.Bytes([]byte(input))
    // ...
    buf, err := envsubst.ReadFile("filename")
}

Example input/output

assets/config.yaml shows a configuration template using substitution forms. assets/file.tmpl is a sample template and assets/file.out its expected output after substitution.

License

MIT