Skip to main content

shtemplate

Lianes8 Certified

POSIX shell parameter expansion ($VAR, ${VAR:-default}, ${VAR%pattern}, ...) over any mapping, with a command line tool. Typed, safe for untrusted templates, zero dependencies.

Outputs are cross-checked against dash and bash --posix on a corpus of more than 1,600 templates. Nothing in a template is ever executed.

Install

pip install shtemplate

Usage

from shtemplate import expand

values = {"USER": "ada", "HOME": "/home/ada", "FILE": "report.tar.gz", "EMPTY": ""}

expand("$HOME/${APP:-demo}", values)  # "/home/ada/demo"
expand("${EMPTY:-guest} [${EMPTY-guest}]", values)  # "guest []"
expand("${USER:+signed in as $USER}", values)  # "signed in as ada"
expand("${CONF:-${XDG:-$HOME/.config}}/app", values)  # "/home/ada/.config/app"

# Pattern removal and length
expand("${FILE%.gz} ${FILE%%.*} ${FILE#*.} ${FILE##*.}", values)  # "report.tar report tar.gz gz"
expand("${#USER}", values)  # "3"

# Required values raise a typed error that names the variable
expand("${TOKEN:?}", values)  # ParameterError: TOKEN: required parameter is missing

# Escapes: \$ and $$ are a literal dollar
expand("price \\$5 or $$5", values)  # "price $5 or $5"

env is any Mapping[str, str] and is never mutated. It defaults to an empty mapping, so nothing is read from the process environment unless you pass os.environ yourself.

Strict and safe modes

from shtemplate import expand

expand("$MISSING", {}, strict=True)  # UnsetVariableError: undefined variable: MISSING ...
expand("${MISSING:-ok}", {}, strict=True)  # "ok": the default handles the unset case

expand("$(rm -rf ~)", {})  # "$(rm -rf ~)": never run; nested parameters still expand
expand("$(rm -rf ~)", {}, safe=True)  # UnsafeTemplateError: command substitution ...

strict=True behaves like set -u. safe=True is meant for templates you do not trust: it rejects $(...), $((...)) and backquotes, caps the output at one million characters (max_output= to change it) and bounds pattern matching work to match.

Inspecting and escaping

from shtemplate import escape, expand, list_vars

list_vars("$HOME/${APP:-demo}/${LOG:-$HOME/log}")  # ["HOME", "APP", "LOG"]
expand(escape("cost: $5"), {})  # "cost: $5"

Assignment

${NAME:=word} and ${NAME=word} substitute word and make it visible to later references in the same template. The mapping you pass is read-only to shtemplate; collect the assignments with assigned= (pass the same dict as env to update it in place).

from shtemplate import expand

sink: dict[str, str] = {}
expand("${PORT:=8080} on $PORT", {}, assigned=sink)  # "8080 on 8080"; sink == {"PORT": "8080"}

Supported forms

Form Result
${NAME} the value; empty if unset (an error in strict mode)
$NAME same, using the longest valid name
${NAME:-word} word if unset or empty
${NAME-word} word if unset
${NAME:=word} word if unset or empty, and assign it
${NAME=word} word if unset, and assign it
${NAME:+word} word if set and not empty, else empty
${NAME+word} word if set, else empty
${NAME:?word} raise ParameterError if unset or empty
${NAME?word} raise ParameterError if unset
${#NAME} the length in characters
${NAME%word} remove the shortest suffix matching the pattern word
${NAME%%word} remove the longest matching suffix
${NAME#word} remove the shortest matching prefix
${NAME##word} remove the longest matching prefix
$$ a literal $
\$NAME a literal $NAME (backslash also escapes backquote and backslash)

word is expanded only when it is needed, so it may contain other expansions. Patterns use shell notation: *, ?, [a-z], [!...], [[:alpha:]] and backslash or quotes for literal characters. Malformed templates raise TemplateSyntaxError with the position. Every template error is an ExpansionError, which is a ValueError. The GUIDE covers the exact rules, the design decisions and the differences from the shell and from string.Template.

Command line

echo 'Hello ${USER:-world}' | shtemplate
shtemplate config.tpl -o config.ini
shtemplate -i --env-file prod.env --set PORT=8080 config.tpl
shtemplate --strict --safe untrusted.tpl
shtemplate --list-vars config.tpl

Variables come from the process environment, then each --env-file (NAME=VALUE lines, never expanded), then each --set. -i starts from an empty environment. Errors go to stderr with exit status 1. python -m shtemplate works too.

Why

Python's string.Template understands $NAME and ${NAME} only: no defaults, no required values, no pattern removal. os.path.expandvars silently leaves unknown names in place and reads only os.environ. shtemplate gives you the documented subset of shell parameter expansion as a pure function over a mapping you choose, with typed errors, a strict mode, a safe mode for untrusted input and a CLI that does what envsubst does, plus defaults, required values and pattern removal.

Development

Install .[dev] and run scripts/check.ps1. Fetch the optional specification with python scripts/fetch_upstream.py; SHTEMPLATE_UPSTREAM can select its local directory. Set SHTEMPLATE_E2E=1 for wheel, CLI and PyPI upgrade checks. TEMP and TMP select the scratch directory; pass pytest --basetemp explicitly for test files. See the CHANGELOG for changes and upgrade notes.

License

MIT. See LICENSE.

Metadata

Release files for shtemplate 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for shtemplate 1.0.0
File Size Uploaded Provenance Actions
shtemplate-1.0.0.tar.gz 76.2 kB Without provenance Details for shtemplate-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for shtemplate 1.0.0
File Interpreter ABI Platform Actions
shtemplate-1.0.0-py3-none-any.whl Python 3 none any Details for shtemplate-1.0.0-py3-none-any.whl

Total release size: 97.2 kB

Release files / shtemplate-1.0.0.tar.gz

Download URL shtemplate-1.0.0.tar.gz
Size 76.2 kB
Tags Source
SHA-256 checksum
How to use checksums
62e664260cf1547d930ab4e69137d41b9376308efec28693e07a8d8d43df065a
BLAKE2b-256 checksum
How to use checksums
188ad7fc592f2083de9bf216ed2926a0b15d5f5d47d13ab94793e086345391fd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.2

Release files / shtemplate-1.0.0-py3-none-any.whl

Download URL shtemplate-1.0.0-py3-none-any.whl
Size 21.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f134fad358075dd533be2f774562e59fe420c3107869de98e3fa81939467fcf3
BLAKE2b-256 checksum
How to use checksums
e49219f45bff372557d59365ba851321342b9b69e5257ddaa51c00efef081c5a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.2

Security for shtemplate 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page