Env Fallback
Options can be populated from environment variables when they are not provided
on the command line. The .env field on any option names the environment
variable to check. The same type conversion and validation pipeline runs
regardless of whether the value came from the CLI or the environment.
Source
Source: examples/env_fallback.cc
examples/env_fallback.cc
#include <iostream>
#include "cli/argument.hh"
#include "cli/parser.hh"
struct Args {
cli::Description description{
"Shows env-var fallback with validation: options can be set via CLI "
"flags or environment variables, and the same validation applies to "
"both."};
cli::Help<> help;
cli::Arg<"threads", 't',
cli::conversion::integer<int> | cli::validation::range<1, 32> |
cli::pack::set_once>
threads{{.help = "Worker threads 1-32 (env: NUM_THREADS)",
.presence = cli::required,
.env = "NUM_THREADS"}};
cli::Arg<"config", 'c',
cli::conversion::string | cli::validation::matches<".*\\.toml"> |
cli::pack::set_once>
config{{.help = "Config file *.toml (env: CONFIG_FILE)",
.presence = cli::optional,
.env = "CONFIG_FILE"}};
cli::Flag<"verbose", 'v'> verbose{{.help = "Verbose output (env: VERBOSE)",
.presence = cli::optional,
.env = "VERBOSE"}};
cli::Positional<std::string> job{
{.help = "Job name to run", .presence = cli::required}};
};
auto main(int argc, char* argv[]) -> int {
const auto args = cli::parse_or_exit<Args>(argc, argv);
if (args.verbose.value()) {
std::cout << "verbose: true\n";
}
std::cout << "threads: " << *args.threads << '\n';
if (args.config) {
std::cout << "config: " << *args.config << '\n';
}
std::cout << "job: " << *args.job << '\n';
return 0;
}
What This Example Shows
--threads/NUM_THREADS— an integer option withrange<1, 32>validation. IfNUM_THREADSis set in the environment, it is parsed and validated exactly like a CLI argument. A value outside 1–32 is an error.--config/CONFIG_FILE— a string option withmatches<".*\\.toml">validation. The env value must end in.tomlor parsing fails.--verbose/VERBOSE— a flag. When the env var is present (any value), the flag is set totrue.- CLI takes precedence — if the option is supplied on the command line, the environment variable is ignored.
Try It
Edit the environment variables in the panel below, then run the program.
The virtual filesystem for this playground contains the following config files
you can reference as CONFIG_FILE:
| Path | Notes |
|---|---|
dev.toml | local development |
test.toml | test environment |
staging.toml | staging environment |
prod.toml | production |
Environment
=
=
cli20@cli20-dev:~$ env_fallback
Things to try:
- Switch environment — change
CONFIG_FILEtostaging.tomlorprod.toml - CLI overrides env —
--config test.toml build-jobwhileCONFIG_FILEis set - Validation via env — set
NUM_THREADS=99to see a range error - Bad config name — set
CONFIG_FILE=settings.jsonto see the regex fail - Verbose from env — add
VERBOSE=1and runbuild-job - Help —
--help