Search code examples
rustclap

How to extract config value from env variable with clap derive?


I cannot find in the docs how to set this up. Let's say I have

#[derive(Parser, Debug)]
pub struct Opts {
    #[clap(long)]
    dry_run: bool,
}

What do I need to do to get dry_run from APP_DRY_RUN env variable?


Solution

  • You have to enable the env feature:

    Cargo.toml

    ...
    
    clap = { version = "...", features = ["env"] }
    

    Then you have to add the env clap derive option, which will by default read from an ALLCAPS recased env var:

    #[derive(Parser, Debug)]
    pub struct Opts {
        #[clap(long, env)]
        dry_run: bool, // --dry-run or DRY_RUN env var
    }