Envsubst: Difference between revisions

From Leo's Notes
This page was last edited on 30 December 2021, at 01:32.
Created page with "<code>envsubst</code>, short for '''env'''ironment '''subst'''itution, makes it easy to substitute environment variables in a text file. This is a simple way to template files..."
 
m Updated categories
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
<code>envsubst</code>, short for '''env'''ironment '''subst'''itution, makes it easy to substitute environment variables in a text file. This is a simple way to template files.
<code>envsubst</code>, short for '''env'''ironment '''subst'''itution, makes it easy to substitute environment variables in a text file. This is a simple way to template files.


== Usage ==
==Usage==
<code>envsubst</code> can replace variables in the form of <code>${VAR}</code> and <code>$VAR</code> with the value defined as an environment variable. The template file is piped to <code>envsubst</code>.
<code>envsubst</code> can replace variables in the form of <code>${VAR}</code> and <code>$VAR</code> with the value defined as an environment variable. The template file is piped to <code>envsubst</code>.


Line 26: Line 26:
| lang = bash
| lang = bash
}}
}}
To use default variables, you can use
 
{{Navbox Linux}}
[[Category:Linux]]
[[Category:LinuxUtilities]]

Latest revision as of 01:32, 30 December 2021

envsubst, short for environment substitution, makes it easy to substitute environment variables in a text file. This is a simple way to template files.

Usage

envsubst can replace variables in the form of ${VAR} and $VAR with the value defined as an environment variable. The template file is piped to envsubst.

A simple example with one variable:

$ export FirstName=leo
$ echo "hello ${FirstName}" | envsubst
hello leo

To save the generated output, simply redirect it to a file.

$ export FirstName=leo
$ echo "hello ${FirstName}" | envsubst > hello.txt

While envsubst isn't capable of supporting more advanced shell features such as ${VAR:-default_value}, you can still make use of it inside a shell script.

#!/bin/bash

## If no argument is passed, FirstName will be set to 'stranger'
FirstName="${1:-stranger}"
echo "Hello there, $FirstName" | envsubst