How to Write Shell Completions for Rust CLIs

Cli
Generate shell completions for Rust CLIs using the clap_complete crate by defining a Command and running the generator for your target shell.

Use the clap_complete crate to generate shell completion scripts for your Rust CLI by defining a Command and running the generator for your target shell. Add clap and clap_complete to your Cargo.toml, define your command structure in main.rs, and run the generator to output the script.

use clap::{Command, Arg, value_parser};
use clap_complete::{generate, shells::Bash, Generator};
use std::io;

fn build_cli() -> Command {
    Command::new("my-cli")
        .version("0.1")
        .arg(
            Arg::new("input")
                .short('i')
                .long("input")
                .value_parser(value_parser!(String))
                .help("Sets the input file to use")
        )
}

fn main() {
    let mut cmd = build_cli();
    generate(Bash, &mut cmd, "my-cli", &mut io::stdout());
}

Run cargo run > my-cli.bash to generate the script, then source it in your shell.