Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions examples/env-substitution
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
BASE_URL=http://localhost
PORT=8080

# ${VAR} syntax works for all variable names
API_URL=${BASE_URL}:${PORT}/api
HEALTH_URL=${BASE_URL}:${PORT}/health

# $VAR syntax works when the name contains only alphanumeric characters
GREETING=hello
MESSAGE=$GREETING world

# Variables defined earlier in the file can be referenced
DB_HOST=db.local
DB_PORT=5432
DB_NAME=myapp
DATABASE_URL=postgres://${DB_HOST}:${DB_PORT}/${DB_NAME}

# Single quotes prevent substitution
LITERAL='${BASE_URL} is not expanded here'

# Escaped dollar sign is treated literally
ESCAPED=\$BASE_URL
8 changes: 8 additions & 0 deletions examples/substitution/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "substitution-example"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
dotenvy = { path = "../../dotenvy" }
40 changes: 40 additions & 0 deletions examples/substitution/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
//! Demonstrates variable substitution in `.env` files.
//!
//! dotenvy supports referencing previously defined variables using `$VAR` or
//! `${VAR}` syntax. Use `${VAR}` when the variable name contains underscores.
//! Single-quoted values and escaped dollar signs (`\$`) are treated literally.
//!
//! Run with: `cargo run`

use dotenvy::{EnvLoader, EnvSequence};
use std::error;

fn main() -> Result<(), Box<dyn error::Error>> {
let env_map = EnvLoader::with_path("../env-substitution")
.sequence(EnvSequence::InputOnly)
.load()?;

println!("--- Variable Substitution Demo ---\n");

println!("Base values:");
println!(" BASE_URL = {}", env_map.var("BASE_URL")?);
println!(" PORT = {}", env_map.var("PORT")?);

println!("\nSubstituted with ${{VAR}} syntax:");
println!(" API_URL = {}", env_map.var("API_URL")?);
println!(" HEALTH_URL = {}", env_map.var("HEALTH_URL")?);

println!("\nSubstituted with $VAR syntax:");
println!(" MESSAGE = {}", env_map.var("MESSAGE")?);

println!("\nComposed DATABASE_URL:");
println!(" DATABASE_URL = {}", env_map.var("DATABASE_URL")?);

println!("\nSingle quotes prevent substitution:");
println!(" LITERAL = {}", env_map.var("LITERAL")?);

println!("\nEscaped dollar sign:");
println!(" ESCAPED = {}", env_map.var("ESCAPED")?);

Ok(())
}