IN-Decent

Re-decentralizing internet with free software

Templating in Shell With envsubst

Posted at — Oct 13, 2023

Templating is a great feature for generating dynamic content and formatting messages instead of manually fiddling with text contents. It separates the data from code, reduces code complexity and keeps the program more readable and maintainable. Having this feature in shell scripts is extremely useful to avoid reaching out to python or other programming languages just for complex text manipulations.

envsubt command which is part of GNU gettext package provides support for templating in shells.

envsubt copies the standard input to standard output, with references to environment variables of the form ‘$VARIABLE’ or ‘${VARIABLE}’ being replaced with the corresponding values. If a referenced environment variable is not present, it is replaced with empty string.

Below is the syntax for the envsubst command,

envsubst [OPTION] [SHELL‐FORMAT]

If SHELL-FORMAT is given, only those environment variables that are referenced in SHELL-FORMAT are substituted.

Usage

Consider a scenario of sending mails to multiple users with user specific content to show how envsubst can be used to simplify the code.

# a sample welcome mail to be sent to new users
$ cat - > welcome-template.txt
Hi ${USERNAME},

Your registration to our website is successfully completed.
Please find below your username and initial password to login to our website.

Username=${USERNAME}
Password=${PASSWORD}

Password change will be prompted after first login.
Your regitered email address: ${EMAIL}

Thankyou,
Admin

User data input is stored in a separate csv file as shown below,

# USERNAME,PASSWORD,EMAIL
$ cat user_data.csv
user1,pass1,user1@company.com
user2,pass2,user2@company.com
user3,pass3,user3@company.com
user4,pass4,user4@company.com

Once the template is created now mail can be sent to users like below,

#!/bin/bash

while read -r USERNAME PASSWORD EMAIL ;
do
export USERNAME PASSWORD EMAIL
envsubst < welcome-template.txt | mail -s "welcome mail" "$EMAIL"
unset USERNAME PASSWORD EMAIL
done <<< $(cat user_data.csv | tr ',' ' ')

References:

  1. man envsubst