bashexpand 0.1.1

Bash-style parameter expansion (${var:-default}, ${var@L}, ${var##pat}, ...) over any variable source: maps, closures, the environment, or your own backend.
Documentation
  • Coverage
  • 100%
    25 out of 25 items documented7 out of 15 items with examples
  • Size
  • Source code size: 90.6 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 514.3 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 2s Average build duration of successful builds.
  • all releases: 3s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • anprowh/bashexpand
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • anprowh

bashexpand

Bash-style parameter expansion — including the advanced operators — over any variable source: maps, closures, the environment, or your own backend.

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)?, "Hello, World!");
assert_eq!(expand("${path##*/}", &mut vars)?,     "tool.tar.gz");
assert_eq!(expand("${missing:-fallback}", &mut vars)?, "fallback");
# Ok::<(), bashexpand::Error<std::convert::Infallible>>(())

Unlike shellexpand/subst (which stop at $var and ${var:-default}), this crate implements the full operator set: substrings, glob prefix/suffix removal, replacements, case modification, and @ transforms. Unlike embedding a full shell, it has zero dependencies, no unsafe, and no shell semantics you didn't ask for — no command substitution, no word splitting, no surprises.

Syntax cheat sheet

Syntax Meaning Example → result
$var, ${var} plain expansion ${name} → world
${var:-word} default if unset or empty ${nope:-x} → x
${var-word} default if unset only ${empty-x} → ``
${var:=word} default + assign (writable ctx) ${n:=1} → 1, stores n=1
${var:+word} alternate if set ${name:+yes} → yes
${var:?msg} error if unset/empty Error::Required
${#var} length (chars) ${#name} → 5
${!var} indirection ptr=name → ${!ptr} → world
${var:off:len} substring, negatives ok ${path: -6} → tar.gz
${var#pat} / ## strip shortest/longest prefix ${path##*/} → tool.tar.gz
${var%pat} / %% strip shortest/longest suffix ${path%%.*} → /usr/local/bin/tool
${var/p/r} / // replace first / all ${path//\//_}
${var/#p/r} / /% replace anchored prefix/suffix
${var^} ^^ , ,, case modification (+ optional glob) ${name^^} → WORLD
${var@U} @u @L upper / capitalize / lower ${name@U} → WORLD
${var@Q} shell-quote safely ${f@Q} → 'my file'
${var@E} expand \n \t \r \0 \\
\$ literal dollar

Globs support *, ?, [a-z], [!a-z], \x. Operator words are recursively expanded (${a:-${b:-c}}).

Variable names are _ and alphanumerics and may start with a digit: $1 / ${1} look up the variable named 1 in your context, just as bash reads its positional parameters. Like bash ("cannot assign in this way"), assigning to such a name (${1:=x}) is an error.

Recipes

Inline closure — no map needed

use bashexpand::expand;

// Annotate `&str` so inference picks the Context impl.
let mut ctx = |name: &str| match name {
    "user" => Some("alice".to_string()),
    "host" => Some("example.com".to_string()),
    _ => None,
};
assert_eq!(expand("${user}@${host}:${port:-22}", &mut ctx)?, "alice@example.com:22");
# Ok::<(), bashexpand::Error<std::convert::Infallible>>(())

Environment variables with defaults

use bashexpand::{expand, Env};

let editor = expand("${EDITOR:-${VISUAL:-vi}}", &mut Env)?;
assert!(!editor.is_empty());
# Ok::<(), bashexpand::Error<std::convert::Infallible>>(())

Layered lookup: overrides → env → defaults

use bashexpand::{expand, ContextExt};
use std::collections::HashMap;

let cli      = HashMap::from([("PORT".into(), "9999".into())]);
let defaults = HashMap::from([("PORT".into(), "8080".into()),
                              ("HOST".into(), "0.0.0.0".into())]);

let mut ctx = cli.chain(defaults);      // first hit wins; chains nest
assert_eq!(expand("${HOST}:${PORT}", &mut ctx)?, "0.0.0.0:9999");
# Ok::<(), bashexpand::Error<std::convert::Infallible>>(())

Fallible backends (database, RPC, files)

use bashexpand::{expand, Error, TryFn};
# fn read_secret(name: &str) -> Result<Option<String>, std::io::Error> { Ok(None) }

let mut ctx = TryFn(|name: &str| -> Result<Option<String>, std::io::Error> {
    read_secret(name)   // Ok(None) = unset; Err = surfaced as Error::Context
});
# let _ = expand("${x:-d}", &mut ctx);

Or implement Context directly for full control (writability, caching, name mangling) — it's two methods, one of them optional. See examples/custom_backend.rs.

Config templating with hard requirements

# use bashexpand::expand;
# use std::collections::HashMap;
# let mut vars: HashMap<String, String> = HashMap::new();
let template = "data = ${DATA_DIR:?DATA_DIR is required}";
match expand(template, &mut vars) {
    Err(bashexpand::Error::Required { var, message }) =>
        eprintln!("config error: {var}: {message}"),
    other => { /* ... */ }
}

Path one-liners

Task Expression
basename ${f##*/}
dirname ${f%/*}
extension ${f##*.}
strip extension ${f%.*}
swap extension ${f%.gz}.xz

Read-only expansion over a shared &map

use bashexpand::expand;
use std::collections::HashMap;

fn render(template: &str, vars: &HashMap<String, String>) -> String {
    // `&map` is itself a Context: no clone, no mutation possible —
    // `${var:=default}` returns Error::AssignUnsupported instead of writing.
    expand(template, &mut &*vars).unwrap()
}

Untrusted templates

use bashexpand::Expander;
# use std::collections::HashMap;
# let mut vars: HashMap<String, String> = HashMap::new();
# let user_template = "${greeting:-hello}";

// Tighten the nesting limit for hostile input; glob matching is already
// linear-time, and there is no command substitution to worry about.
let out = Expander::new().max_depth(8).expand(user_template, &mut vars)?;
# Ok::<(), bashexpand::Error<std::convert::Infallible>>(())

Non-goals

Arrays, positional/special parameter semantics ($@, $?), command substitution $(...), arithmetic $((...)), extglobs @(...), POSIX classes [[:alpha:]], and the @P/@A/@K/@a transforms. If you need bash-the-language, look at brush.

MSRV & safety

Rust 1.70+. #![forbid(unsafe_code)], zero dependencies. Depth-limited recursion and linear-time glob matching make it safe to run on untrusted template input.

License

MIT