Get value of one command line argument if exists

I want to get the value of one command line argument if it exists. Many other arguments may be present as well. What is the best way or best library to do this? For example, the if "--max 100" is in the arguments, I want to recover 100.

A commonly used crate for this kind of functionality is the crate clap, though of course you could also try to manually make sense of the contents of https://doc.rust-lang.org/stable/std/env/fn.args.html.

2 Likes

Here an example of using a clap builder:

use clap::{arg, command, value_parser};

fn main() {
    let matches = command!()
        .arg(
            arg!(--max <VALUE>)
                .value_parser(value_parser!(u32))
                .required(true),
        )
        .get_matches();

    let max = matches.get_one::<u32>("max").unwrap();
}

I don't want clap to return an error if the variable I am looking for doesn't exist. For example if i pass in "--foo 22", it will cause an error.

Ah, I see. I actually don't know how to allow unknown arguments in clap. How about this instead, then:

fn main() {
    let max: u32 = std::env::args()
        .skip_while(|x| x != "--max")
        .nth(1)
        .unwrap()
        .parse()
        .unwrap();

    println!("{max}");
}

try_get_matches doesn't throw an error.

Here is the function I came up with to solve my problem.

fn get_cli_argument (argument: &'static str)-> Option<std::string::String>{
    let matches = Command::new("")
      .arg(Arg::new(argument)
      .long(argument)
    ).try_get_matches();
    
    if matches.is_ok() {
      matches.unwrap().get_one::<String>(argument).cloned()
    } else {
      None
    }
}

Please use clippy

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.