Sub topic 9
Defaults and environment variables
This chapter assumes you can define a derived parser with #[derive(Parser)] and that you know how options, flags and value_parser work. It covers what a program does when the user leaves an option out: use a built-in default, read an environment variable, or fail.
The order clap checks for a value
For every argument, clap looks for a value in a fixed order and stops at the first source that has one:
- The command line.
- The environment variable named by
env. - The default from
default_valueordefault_value_t. - Nothing. An
Option<T>field becomesNone, and a required argument produces an error.
Every value that comes from steps 1 to 3 goes through the same value_parser. A bad value in an environment variable is rejected the same way as a bad value typed on the command line.
Enabling the env feature
Reading environment variables is behind a Cargo feature. Without it, the env attribute does not compile.
[dependencies]
clap = { version = "4", features = ["derive", "env"] }Defaults: two attributes
default_value takes a string. clap runs that string through the value parser, as if the user had typed it.
default_value_t takes a Rust expression of the field's type. clap converts it to text with Display, then parses it like any other value. That keeps the default visible in --help.
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
/// Port to listen on
#[arg(long, default_value_t = 8080)]
port: u16,
/// Directory to serve
#[arg(long, default_value = ".")]
root: std::path::PathBuf,
}
fn main() {
println!("{:?}", Cli::parse());
}Running it with no arguments prints:
Cli { port: 8080, root: "." }The help output shows [default: 8080] and [default: .] next to the options.
Use default_value_t when the type implements Display. PathBuf does not, so root uses the string form. Enums that derive ValueEnum also work with default_value_t, as in default_value_t = Priority::Normal from the subcommands chapter. clap prints the default using the enum's command-line name, such as normal.
A field with a default is never missing, so the type should be T, not Option<T>. If you write Option<T> and a default, clap fills the default and you wrap it in Some for no reason. Use Option<T> only when "not given" is a meaningful state.
Defaults for optional values
Some options can be given with no value, as in --log versus --log=debug. The attribute default_missing_value supplies the value used when the option appears without one. It works together with num_args = 0..=1.
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
/// Log level. A bare --log means info.
#[arg(
long,
default_value = "warn",
num_args = 0..=1,
require_equals = true,
default_missing_value = "info"
)]
log: String,
}
fn main() {
println!("{:?}", Cli::parse());
}This gives three different results:
| Command line | `log` |
|---|---|
| (no `--log`) | `warn` |
| `--log` | `info` |
| `--log=debug` | `debug` |
require_equals = true forces the --log=debug spelling. Without it, --log debug is ambiguous when the program also has a positional argument, because clap cannot tell whether debug is the option's value or the positional.
Environment variable fallbacks
env = "NAME" tells clap to read NAME when the argument is absent from the command line.
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
/// Port to listen on
#[arg(long, env = "APP_PORT", default_value_t = 8080)]
port: u16,
/// API token
#[arg(long, env = "APP_TOKEN", hide_env_values = true)]
token: Option<String>,
}
fn main() {
println!("{:?}", Cli::parse());
}Try the three sources in turn:
cargo run
# Cli { port: 8080, token: None }
APP_PORT=9000 cargo run
# Cli { port: 9000, token: None }
APP_PORT=9000 cargo run -- --port 7000
# Cli { port: 7000, token: None }The command line beats the environment, and the environment beats the default. This matches the convention in most Unix tools, and it lets a user set a long-lived value in their shell profile and override it for one run.
If you write #[arg(long, env)] with no name, the derive macro uses the field name in upper case, so token reads TOKEN. Prefer an explicit, prefixed name such as APP_TOKEN. Generic names collide with variables other programs set.
Invalid values from the environment
If APP_PORT=abc is set, clap does not silently fall back to the default. It runs abc through the u16 parser and exits with a usage error that names --port. The user then sees a complaint about an option they never typed. For a tool where this will confuse people, mention the variable in the help text so they can find the cause.
Environment variables and flags
A boolean flag declared with ArgAction::SetTrue can also have an env. clap reads the variable as a boolean, so values such as true, false, 1 and 0 work. A plain -v counter (ArgAction::Count) is a poor fit for env, because "how many times it appeared" has no natural environment form.
Showing and hiding in help
clap adds [env: APP_PORT=9000] to the help line when the variable is set, and [env: APP_PORT] when it is not. Two attributes control this:
hide_env_values = truekeeps the variable name in the help but never prints its current value.hide_env = trueremoves the variable from the help entirely.hide_default_value = trueremoves the[default: ...]note.
Required arguments and defaults
A default or an environment variable satisfies a required argument. This is useful for options that must have a value but have a sensible fallback.
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
/// Database URL (required, but may come from DATABASE_URL)
#[arg(long, env = "DATABASE_URL")]
database_url: String,
}
fn main() {
println!("{:?}", Cli::parse());
}Because the field is String and has no default, clap treats it as required. With DATABASE_URL set, cargo run works. Without it, clap prints the following required arguments were not provided: --database-url <DATABASE_URL> and exits with code 2.
Common mistakes
- Forgetting the
envfeature. The error is a compile failure on theenvattribute, not a runtime message. - Using
default_value_twith a type that has noDisplay. Switch to the string formdefault_value = "...". - Choosing a default that fails the value parser. A
default_value = "70000"on au16fails when the argument is parsed. CallingCli::command().debug_assert()in a test, as the testing chapter shows, catches many of these mistakes at test time. - Testing environment-dependent code with
std::env::set_var. Tests run in parallel threads and share one environment, so tests that set variables can interfere with each other. Prefer testing the command-line and default paths withtry_parse_from, and keepenvtests few and serial. - Assuming defaults apply per subcommand automatically. A default belongs to the argument where you declare it. A subcommand's argument has its own default.
Exercise
A struct has #[arg(long, env = "APP_PORT", default_value_t = 8080)] port: u16. The shell has APP_PORT=9000 exported, and the user runs app --port 7000. Which port does the program use, and what happens if the user instead exports APP_PORT=abc and runs app with no arguments?
Show answer
With both set, the program uses 7000, because the command line has the highest precedence. With APP_PORT=abc and no --port, clap does not fall back to 8080. It parses abc as a u16, fails, prints a usage error that refers to --port, and exits with code 2.
Exercise
You want --color to mean auto when absent, always when written as a bare --color, and any of auto, always, never when written as --color=VALUE. Which attributes do you need?
Show answer
Declare the field with #[arg(long, value_enum, default_value_t = Color::Auto, num_args = 0..=1, require_equals = true, default_missing_value = "always")], where Color derives ValueEnum. default_value_t covers the absent case, default_missing_value covers the bare flag, and require_equals avoids ambiguity with positional arguments.