Sub topic 1
What a command-line interface is made of
Every command-line tool you write with clap starts from the same raw material: a list of text words that the operating system hands to your program. This chapter describes that raw material and the vocabulary used for its parts. The rest of the tutorial builds on these terms: positional arguments, options, flags, and subcommands.
Prerequisites
This chapter assumes you can do the following:
- Read basic Rust: structs, enums,
Option,Result, and ownership. - Create, build, and run a project with Cargo.
- Use command-line programs in a terminal, including flags and exit codes.
You do not need clap yet. This chapter uses only the standard library.
From a typed line to your program
When you type a command and press Enter, the shell does the first round of work. It splits the line into words, expands things like ~ and *, and removes quotes. It then starts the program and passes the resulting list of strings. That list is called argv (argument vector).
Your program never sees the line you typed. It sees the words after the shell has processed them. Here is a program that prints exactly what it receives:
fn main() {
for (i, arg) in std::env::args().enumerate() {
println!("argv[{i}] = {arg:?}");
}
}Save it as src/main.rs in a new Cargo project named anatomy, then run it:
cargo run -q -- --filter error "my file.txt" -vvThe output looks like this. The first line depends on your platform and build profile:
argv[0] = "target/debug/anatomy"
argv[1] = "--filter"
argv[2] = "error"
argv[3] = "my file.txt"
argv[4] = "-vv"Three details matter here:
argv[0]is the program's own path. A parser skips it, but it is where the program name in usage messages comes from.- The quotes around
my file.txtare gone. The shell used them to keep the space inside one word, so the program receives one argument. cargo runhas its own options. The bare--tells Cargo that everything after it belongs to your program.
Nothing in argv says which words are options and which are values. --filter and error are both just strings. Deciding that error is the value of --filter is the job of an argument parser, and that is what clap does.
The four kinds of element
Most command lines are built from four kinds of element. Take a hypothetical tool called tasks:
tasks --verbose add "Write report" --priority high -t workHere is each element in that line:
- Subcommand:
add. A word that selects a mode of the program, likegit commitorcargo build. Each subcommand can have its own arguments. - Positional argument:
"Write report". A value identified only by its position, not by a name. - Option:
--priority highand-t work. A named argument that takes a value. Also called a named argument. - Flag:
--verbose. A named argument that takes no value. Its presence turns something on.
| Element | Looks like | Has a value | Identified by | Typical use |
|---|---|---|---|---|
| Positional argument | `report.txt` | Yes | Position | The main input, such as a file or a title |
| Option | `--priority high` | Yes | Name | A setting with a value |
| Flag | `--verbose` | No | Name | An on/off switch or a counter |
| Subcommand | `add` | No | Name, then its own arguments | Selecting one of several actions |
The distinction between option and flag matters for parsing. When the parser sees --priority, it must consume the next word as the value. When it sees --verbose, it must not. The parser knows this only because your program declared it. This is why clap needs a description of your CLI before it can read argv.
Short names, long names, and spelling variations
Options and flags usually have two spellings:
- A long name with two dashes, such as
--verbose. It is readable and self-documenting, and it is the one you use in scripts. - A short name with one dash and one character, such as
-v. It is quick to type.
Conventions that most Unix-style tools follow, and that clap supports:
- Short flags can be bundled:
-abcmeans-a -b -c. - A short flag can be repeated to count:
-vvoften means "more verbose than-v". - A value can be attached with
=for long names:--priority=highis the same as--priority high. - A short option can take its value attached directly:
-t workand-tworkare equivalent.
These forms are all valid for a program that declares the right options, but the program receives them differently. -vv arrives as a single string "-vv", not two. Splitting it is the parser's job.
Two special words: `--` and `-`
A bare -- means "stop looking for options". Everything after it is a positional argument, even if it starts with a dash. That is how you operate on a file whose name looks like a flag:
rm -- -weird-file-nameA single - conventionally means standard input or standard output instead of a file. It is just a word to the shell. Your program decides to treat it specially.
Everything else a CLI communicates
Arguments are the input side. A well-behaved tool also has a defined output side.
- Standard output (stdout) carries the program's real results. Other programs may read it through a pipe.
- Standard error (stderr) carries diagnostics and error messages. Keeping them apart means
tool | wc -lcounts results, not warnings. - Exit code is a small integer returned to the shell.
0means success and any non-zero value means failure. Scripts check it withif,&&, and||. - Environment variables are an input channel besides
argv. Tools use them for configuration such as tokens or default paths.
Here is a small program that follows the stdout, stderr, and exit code conventions without any parser. It requires exactly one argument:
use std::process::ExitCode;
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.len() != 1 {
eprintln!("usage: anatomy <name>");
return ExitCode::from(2);
}
println!("Hello, {}!", args[0]);
ExitCode::SUCCESS
}Try it with zero, one, and two arguments, then inspect $? in a Unix shell:
cargo run -q
echo "exit code: $?"
cargo run -q -- Ada
echo "exit code: $?"The first run prints the usage line to stderr and exits with 2. The second prints Hello, Ada! and exits with 0. Exit code 2 is the conventional choice for "the command line was used incorrectly", and clap uses 2 for its own usage errors.
Why hand-written parsing breaks down
The program above handles one positional argument. Add a few real requirements and the code grows quickly:
- An optional
--filterthat takes a value, in both--filter xand--filter=xforms. - A counted
-vthat also works as-vvand inside a bundle like-av. - Numbers that must be validated, with a clear error naming the bad argument.
--helpand--versionthat stay accurate as the program changes.- A message for a mistyped option, ideally with a suggestion.
Each item is a place for bugs, and users notice inconsistencies. A parser library takes a declaration of what the CLI accepts and produces both the parsing logic and the user-facing text from that single description.
Common mistakes at this stage
- Forgetting that the shell is involved. An unquoted
*or a space changes what your program receives. When debugging, printargvas shown above and look at the actual words. - Mixing up flag and option. A flag has no value. If you find yourself writing
--verbose true, you probably want a flag. - Printing errors to stdout. This corrupts output that another program is reading. Send errors to stderr.
- Returning 0 after a failure. Scripts cannot detect the problem. Return a non-zero code on any failure.
- Assuming non-UTF-8 never happens.
std::env::args()panics if any argument is not valid Unicode. Parsers like clap useargs_osinternally and handle this case by turning it into a normal error. File paths in particular can be non-UTF-8 on Unix.
What comes next
The following chapters add clap to a Cargo project and describe each element from this chapter in code. Positional arguments become fields, options become Option<T> fields, flags become bool or counter fields, and subcommands become enums.
Exercise
A user runs backup --dest "/mnt/my drive" -vv src/ -- -odd-name. List the elements by kind, and say what the final two words are treated as.
Show answer
--dest "/mnt/my drive" is an option with the single value /mnt/my drive, because the shell removes the quotes and keeps the space inside one word. -vv is a counted short flag, delivered as one string -vv. src/ is a positional argument. The bare -- ends option parsing, so -odd-name is a positional argument, not an option, even though it starts with a dash. backup is the program name (argv[0] carries its path), not a subcommand.
Exercise
Why should a tool print its error messages with eprintln! instead of println!, and what exit code should it return after reporting one?
Show answer
Standard output is for results, which other programs may read through a pipe, and standard error is for diagnostics, so error text sent to stderr does not mix into the results. The tool should return a non-zero exit code so scripts can detect failure. Use 2 for incorrect usage, which matches clap's own usage errors, and 1 for other application failures.