home ~ projects ~ socials

Get a Single Command Line Argument with Clap in Rust

Helpful Arguments

clap1 is the Command Line Argument Parser for Rust. It has a billion and one ways to process arguments and flags. Even better, it provides nice error messages out of the box.

There's a bunch of great tutorials2 and a cookbook3 in the docs. As thorough as they are, I didn't see how to use it to get a single argument.

This is what I came up with after a quick dive into the docs:

#!/usr/bin/env cargo -Zscript

---
[dependencies]
clap = "4.5.38"
---

use clap::{Arg, Command};

fn main() {
    let matches = Command::new("runner")
    .arg(Arg::new("thing_to_use")
        .index(1)
        .required(true)
        .help("The thing to use when running the script.")
    )
    .get_matches();

    if let Some(thing_to_use) = matches.get_one::<String>("thing_to_use") {
        println!("Found: {}", thing_to_use);
    }
}

Usage

If you drop that code in a file called runner.rs and run it with:

./runner.rs some_thing

It'll output:

Output
Found: some_thing

Bonus Features

Missing Things

Calling the script without an argument gives you an error:

./runner.rs
Output
Usage: runner <thing_to_use>

For more information, try '--help'.

Automatic Help

Processing a --help flag is built-in. It gives you nice output:

./runner.rs --help
Output
Usage: runner <thing_to_use>

Arguments:
  <thing_to_use>  The thing to use when runnig the script.

Options:
  -h, --help  Print help

One Ping Only

Clap is worth checking out for any and all your command line processing needs. I'd be surprised if you can come up with a realistic example it can't handle.

-a

-- end of line --

Endnotes

This example is set up as a rust script. Yoink the top #! line and move the dependencies into a Cargo.toml file to use it in a traditional binary.

Clap provides a bunch of macros and a couple different ways to build argument parsers. This approach was the easiest for me to get working. You should kick around the docs though to get a feel for the different ways you can use the crate.

Also check out value_parser for validating incoming values.

References

Footnotes