Skip to main content

Crate bsd_getopt

Crate bsd_getopt 

Source
Expand description

§bsd-getopt

A small, dependency-free implementation of a BSD-style getopt parser in Rust.

This crate provides a minimal and predictable way to parse short command-line options (e.g. -a, -b value, -abc) similar to traditional Unix getopt.

§Features

  • Supports grouped options (-abc)
  • Supports options with required arguments (-o value or -ovalue)
  • Handles -- to terminate option parsing
  • Exposes optind, optarg, and optopt like classic getopt
  • No unsafe code, no dependencies

§Example

use bsd_getopt::Getopt;

let args = vec![
    "prog".to_string(),
    "-a".to_string(),
    "-b".to_string(),
    "value".to_string(),
    "-cfoo".to_string(),
];

let mut parser = Getopt::new("ab:c:", args);

while let Some(opt) = parser.next() {
    match opt {
        'a' => println!("option a"),
        'b' => println!("option b with arg {:?}", parser.optarg),
        'c' => println!("option c with arg {:?}", parser.optarg),
        '?' => println!("unknown option: {}", parser.optopt),
        ':' => println!("missing argument for: {}", parser.optopt),
        _ => {}
    }
}

§optstring format

  • a → option without argument
  • b: → option requires argument
  • :abc → suppress error messages, return : on missing argument

§Notes

  • Parsing stops at the first non-option argument or --
  • This crate only supports short options (no long options like --help)

Structs§

Getopt
A BSD-style command-line option parser.