Expand description
Bash-style parameter expansion over any variable source.
bashexpand implements the familiar ${...} expansion syntax from bash,
including the advanced operators (${var:-default}, ${var@L},
${var##*/}, ${var/pat/repl}, …), but lets you decide where
variables come from: a HashMap, a closure, the process environment, a
config store, a database — anything that implements the small Context
trait.
§Quick start
use bashexpand::expand;
use std::collections::HashMap;
let mut vars = HashMap::from([
("name".to_string(), "world".to_string()),
("path".to_string(), "/usr/local/bin/tool.tar.gz".to_string()),
]);
assert_eq!(expand("Hello, ${name^}!", &mut vars).unwrap(), "Hello, World!");
assert_eq!(expand("${path##*/}", &mut vars).unwrap(), "tool.tar.gz");
assert_eq!(expand("${missing:-fallback}", &mut vars).unwrap(), "fallback");Or with an inline closure — no map required:
use bashexpand::expand;
let mut ctx = |name: &str| match name {
"user" => Some("alice".to_string()),
"host" => Some("example.com".to_string()),
_ => None,
};
assert_eq!(expand("${user}@${host}", &mut ctx).unwrap(), "alice@example.com");
assert_eq!(expand("${port:-22}", &mut ctx).unwrap(), "22");§Supported syntax
| Syntax | Meaning |
|---|---|
$var, ${var} | plain expansion (unset expands to "") |
${var:-word} / ${var-word} | default if unset-or-empty / if unset |
${var:=word} / ${var=word} | like :-, but also assigns (needs a writable context) |
${var:+word} / ${var+word} | word if set, else "" |
${var:?msg} / ${var?msg} | error (Error::Required) if unset |
${#var} | length in characters |
${!var} | indirection: expand the variable named by var |
${var:off} / ${var:off:len} | substring; negative offsets/lengths count from the end |
${var#pat} / ${var##pat} | remove shortest/longest matching prefix (glob) |
${var%pat} / ${var%%pat} | remove shortest/longest matching suffix (glob) |
${var/pat/repl} | replace first match |
${var//pat/repl} | replace all matches |
${var/#pat/repl} / ${var/%pat/repl} | replace anchored prefix / suffix match |
${var^} / ${var^^} | uppercase first char / all chars (optional glob: ${var^^[ab]}) |
${var,} / ${var,,} | lowercase first char / all chars |
${var@U} @u @L | uppercase / capitalize / lowercase |
${var@Q} | shell-quote the value |
${var@E} | interpret \n, \t, \r, \0, \\ escapes |
\$ | a literal dollar sign |
Globs support *, ?, [a-z], [!a-z] and \x escapes. Words inside
operators are themselves expanded, so ${a:-${b:-c}} works.
Variable names are _ and alphanumerics and may start with a digit:
$1 / ${1} look up the variable named 1 in the context, just as bash
reads its positional parameters. Like bash (“cannot assign in this way”),
assigning to such a name (${1=x}, ${1:=x}) is an error —
Error::AssignUnsupported.
Non-goals (kept out deliberately; reach for a full shell like
brush if you need them): arrays,
positional/special parameter semantics ($@, $?), command substitution,
arithmetic expansion, extglobs @(...), POSIX classes [[:alpha:]], and
the @P/@A/@K/@a transforms.
§Choosing a context
| You have… | Use |
|---|---|
HashMap<String, String> / BTreeMap<String, String> | pass &mut map directly (writable: := works) |
only a shared &map | pass &mut &map (read-only: := errors) |
| a lookup function | pass &mut closure FnMut(&str) -> Option<String> (read-only) |
| process environment | Env |
| a fallible backend (DB, RPC, files) | TryFn or implement Context |
| several sources with priority | ContextExt::chain |
| custom needs (case-insensitive names, prefixes, …) | implement Context (two methods, one optional) |
§Recipes
Environment variables with defaults — nested fallbacks work anywhere a word does:
use bashexpand::{expand, Env};
let editor = expand("${EDITOR:-${VISUAL:-vi}}", &mut Env).unwrap();
assert!(!editor.is_empty());Layered lookup — CLI overrides beat environment beat defaults; first hit wins and chains nest:
use bashexpand::{expand, ContextExt};
use std::collections::HashMap;
let cli = HashMap::from([("PORT".to_string(), "9999".to_string())]);
let defaults = HashMap::from([
("PORT".to_string(), "8080".to_string()),
("HOST".to_string(), "0.0.0.0".to_string()),
]);
let mut ctx = cli.chain(defaults);
assert_eq!(expand("${HOST}:${PORT}", &mut ctx).unwrap(), "0.0.0.0:9999");Path one-liners — the classic bash idioms all work:
use bashexpand::expand;
use std::collections::HashMap;
let mut v = HashMap::from([("f".to_string(), "/opt/app/logs/app.tar.gz".to_string())]);
assert_eq!(expand("${f##*/}", &mut v).unwrap(), "app.tar.gz"); // basename
assert_eq!(expand("${f%/*}", &mut v).unwrap(), "/opt/app/logs"); // dirname
assert_eq!(expand("${f##*.}", &mut v).unwrap(), "gz"); // extension
assert_eq!(expand("${f%.*}", &mut v).unwrap(), "/opt/app/logs/app.tar"); // strip extension
assert_eq!(expand("${f%.gz}.xz", &mut v).unwrap(), "/opt/app/logs/app.tar.xz"); // swap extensionHard-required variables — turn missing configuration into a typed error with your own message:
use bashexpand::{expand, Error};
use std::collections::HashMap;
let mut vars: HashMap<String, String> = HashMap::new();
match expand("data = ${DATA_DIR:?DATA_DIR is required}", &mut vars) {
Err(Error::Required { var, message }) => {
assert_eq!(var, "DATA_DIR");
assert_eq!(message, "DATA_DIR is required");
}
other => panic!("expected Error::Required, got {other:?}"),
}Read-only expansion over a shared &map — no clone, and assignment
(:=) is a hard error instead of a silent mutation:
use bashexpand::{expand, Error};
use std::collections::HashMap;
let vars = HashMap::from([("host".to_string(), "example.com".to_string())]);
assert_eq!(expand("${host}", &mut &vars).unwrap(), "example.com");
assert!(matches!(
expand("${port:=8080}", &mut &vars),
Err(Error::AssignUnsupported { .. })
));Fallible backends (databases, RPC, files) — lookup failures surface as
Error::Context, never as “unset”:
use bashexpand::{expand, Error, TryFn};
fn read_secret(name: &str) -> Result<Option<String>, std::io::Error> {
match name {
"DB_PASSWORD" => Ok(Some("hunter2".to_string())),
_ => Err(std::io::Error::new(std::io::ErrorKind::NotFound, name.to_string())),
}
}
let mut ctx = TryFn(read_secret);
assert_eq!(expand("pw=${DB_PASSWORD}", &mut ctx).unwrap(), "pw=hunter2");
assert!(matches!(expand("${MISSING}", &mut ctx), Err(Error::Context(_))));Untrusted templates — glob matching is already linear-time and there is no command substitution; tighten the nesting limit and hostile inputs fail fast:
use bashexpand::{Error, Expander};
use std::collections::HashMap;
let mut vars: HashMap<String, String> = HashMap::new();
let expander = Expander::new().max_depth(4);
assert_eq!(expander.expand("${a:-${b:-ok}}", &mut vars).unwrap(), "ok");
let hostile = "${a:-${a:-${a:-${a:-${a:-x}}}}}";
assert_eq!(expander.expand(hostile, &mut vars), Err(Error::TooDeep));§Error handling
expand returns Error<E> where E is the context’s own error type.
Contexts that cannot fail use Infallible,
and you can .unwrap()-free convert with ? in functions returning your
error type. ${var:?}, malformed input, assignment to read-only contexts,
and over-deep nesting are all distinct variants — nothing is silently
swallowed.
§Safety & robustness
- Glob matching is compiled and iterative —
O(pattern × text), immune to the exponential blow-up of naive backtracking (a*a*a*a*b). - Recursive expansions are depth-limited (configurable via
Expander::max_depth) to prevent stack exhaustion on adversarial input. - All operations are
char-based, so Unicode values behave correctly. - No dependencies, no
unsafe.
Structs§
- Chain
- Two contexts layered with fallback; created by
ContextExt::chain. - Env
- Read-only
Contextbacked by the process environment (std::env::var). - Expander
- Configurable expander (builder style).
- TryFn
- Adapter turning a fallible closure into a
Context.
Enums§
- Error
- Everything that can go wrong during expansion.
Constants§
- DEFAULT_
MAX_ DEPTH - Default maximum nesting depth of recursive expansions (
${a:-${b:-...}}).
Traits§
- Context
- A source of variables.
- Context
Ext - Extension methods for every
Context.
Functions§
- expand
- Expand all
$var/${...}expressions ininputusingctx, with default settings.