Programming languages · Intermediate · 25 min
Build a command-line tool in Rust with clap
By Padding · Updated 18 Nov 2026
Debian 13 (rust:1.100 image) · Rust 1.100.0 · clap 4.6.10
You will build dupfind, a Rust 1.100 command-line tool that lists duplicate files in a folder, with clap 4.6 handling its flags, subcommands, output formats and environment variables, tests written with assert_cmd, and a small release binary installed on your PATH.
On this page
A command-line tool lives or dies by its interface: clear help, sensible defaults, errors that say what went wrong, and exit codes a script can test. Writing all of that by hand on top of std::env::args is slow and easy to get wrong. clap does the parsing for you. With its derive feature you describe the interface as an ordinary Rust struct, and clap generates the parser, the --help text, the --version flag and the error messages from it.
In this tutorial you build dupfind. It walks a folder, finds files whose contents are identical, and prints them in groups. It has two subcommands (scan lists the groups, summary prints totals), flags, options with defaults and allowed ranges, an --output format, a setting read from an environment variable, and exit codes that a backup script or a CI job can rely on. You test it as a user would, by running the binary, and finish by building a small release binary and installing it on your PATH.
dupfind only reads. It never moves or deletes a file, which makes it safe to point at real folders while you learn.
Step 1 · Create the project and add clap
Create a project in a throwaway folder. --name sets the package name, which is also the name of the binary:
cargo new ~/dupfind-demo --name dupfind
cd ~/dupfind-demo
cargo add clap@4.6.10 --features derive,envThe derive feature gives you #[derive(Parser)] and the other derive macros. The env feature lets an option fall back to an environment variable. Both are off by default, so clap stays small for programs that do not need them.
cargo add writes the requirement 4.6.10 into Cargo.toml. Cargo reads that as "4.6.10 or any later 4.x", and Cargo.lock records the exact version it chose, so the project builds the same way until you run cargo update.
If you pay for mobile data by the megabyte, note that the first build downloads clap and its dependencies from crates.io. Cargo keeps them in ~/.cargo/registry, so later builds of this and other projects reuse them, and cargo build --offline works once they are there.
Check it worked
grep clap Cargo.tomlThe line reads clap = { version = "4.6.10", features = ["derive", "env"] }.
Step 2 · Describe the command line as Rust types
Put the interface in its own file, src/cli.rs. Every doc comment (///) becomes help text, every field becomes an argument, and each enum variant of Command becomes a subcommand:
cat > src/cli.rs <<'RS'
use std::path::PathBuf;
use clap::{Args, Parser, Subcommand, ValueEnum};
/// Find files with identical contents in a folder.
///
/// dupfind only reads files. It never moves or deletes anything.
#[derive(Debug, Parser)]
#[command(version)]
pub struct Cli {
#[command(subcommand)]
pub command: Command,
}
#[derive(Debug, Subcommand)]
pub enum Command {
/// List every group of duplicate files
Scan {
#[command(flatten)]
common: ScanArgs,
/// Output format
#[arg(long, value_enum, default_value_t = Format::Text)]
output: Format,
},
/// Print totals only: groups, extra copies and wasted bytes
Summary(ScanArgs),
}
/// Options shared by both subcommands.
#[derive(Debug, Args)]
pub struct ScanArgs {
/// Folder to search
#[arg(default_value = ".")]
pub dir: PathBuf,
/// Skip files smaller than this many bytes
#[arg(long, value_name = "BYTES", default_value_t = 1, env = "DUPFIND_MIN_SIZE")]
pub min_size: u64,
/// How many folder levels to search (1 means only DIR itself)
#[arg(long, value_name = "N", default_value_t = 16,
value_parser = clap::value_parser!(u32).range(1..=64))]
pub max_depth: u32,
/// Include hidden files and folders (names starting with a dot)
#[arg(long)]
pub hidden: bool,
/// Exit with code 3 if any duplicates are found
#[arg(long)]
pub check: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum Format {
/// One block per group, for people
Text,
/// One row per file, for spreadsheets and scripts
Csv,
}
RSWhat each piece does:
dirhas nolong, so it is a positional argument.default_value = "."makes it optional.--min-sizeis an option with a default.env = "DUPFIND_MIN_SIZE"lets the environment set it. If both are given, the command line wins, then the variable, then the default.--max-depthusesvalue_parser!(u32).range(1..=64). clap rejects0or500before your code runs, and says which values are allowed.--hiddenand--checkareboolfields, so they are flags: present meanstrue.FormatderivesValueEnum, which turns--output textand--output csvinto enum values and lists the choices in the help.#[command(flatten)]pulls the fields ofScanArgsintoscan, soscanandsummaryshare one definition of the common options while onlyscangets--output.- The doc comment on
Clihas two paragraphs. The first is the short description shown by-h;--helpshows both.
Now replace src/main.rs with a version that parses the arguments and prints what clap produced:
cat > src/main.rs <<'RS'
mod cli;
use clap::Parser;
fn main() {
let cli = cli::Cli::parse();
println!("{cli:#?}");
}
RS
cargo run -q -- scan sample --hidden --output csvCargo may warn that some fields are never read. That is expected until the next steps use them.
Check it worked
The program prints the parsed struct, something like this:
Cli {
command: Scan {
common: ScanArgs {
dir: "sample",
min_size: 1,
max_depth: 16,
hidden: true,
check: false,
},
output: Csv,
},
}Now look at the help clap wrote for you, and try a value outside the allowed range:
cargo run -q -- --help
cargo run -q -- scan -h
cargo run -q -- scan --max-depth 0 || echo "exit code: $?"The top-level help shows the description, Usage: dupfind <COMMAND>, and the scan, summary and help commands. scan -h lists [DIR], every option with its default, [env: DUPFIND_MIN_SIZE=] and [possible values: text, csv]. The last command fails with something like error: invalid value '0' for '--max-depth <N>': 0 is not in 1..=64, and prints exit code: 2. Exit code 2 is clap's code for a usage error.
Step 3 · Find the duplicate files
The search itself goes in src/scan.rs, apart from the interface. It works in two passes, which is what keeps it fast. First it records the size of every file, which costs one metadata lookup per file. Files with a size no other file has cannot be duplicates, so only files that share a size are read and hashed in the second pass. On a typical folder most files are skipped without reading a single byte.
The hash is FNV-1a, a few lines of arithmetic that gives the same 64-bit number for the same bytes on every machine. It is not a cryptographic hash, and two different files can in principle share a value, so treat the output as a list to check before you delete anything, for example with cmp a b.
cat > src/scan.rs <<'RS'
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use crate::cli::ScanArgs;
/// Files that have the same size and the same contents.
pub struct Group {
pub size: u64,
pub paths: Vec<PathBuf>,
}
pub fn find_duplicates(args: &ScanArgs) -> io::Result<Vec<Group>> {
// Pass 1: every regular file, grouped by size.
let mut by_size: HashMap<u64, Vec<PathBuf>> = HashMap::new();
walk(&args.dir, 1, args, &mut by_size)?;
// Pass 2: only files that share a size can match, so hash just those.
let mut groups = Vec::new();
for (size, paths) in by_size {
if paths.len() < 2 {
continue;
}
let mut by_hash: HashMap<u64, Vec<PathBuf>> = HashMap::new();
for path in paths {
match hash_file(&path) {
Ok(hash) => by_hash.entry(hash).or_default().push(path),
Err(e) => eprintln!("dupfind: skipping {}: {e}", path.display()),
}
}
for (_, mut paths) in by_hash {
if paths.len() > 1 {
paths.sort();
groups.push(Group { size, paths });
}
}
}
// Biggest files first: that is where the wasted space is.
groups.sort_by(|a, b| b.size.cmp(&a.size).then_with(|| a.paths.cmp(&b.paths)));
Ok(groups)
}
fn walk(
dir: &Path,
depth: u32,
args: &ScanArgs,
by_size: &mut HashMap<u64, Vec<PathBuf>>,
) -> io::Result<()> {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let hidden = entry.file_name().to_string_lossy().starts_with('.');
if hidden && !args.hidden {
continue;
}
// file_type() does not follow symbolic links, so links are skipped.
let kind = entry.file_type()?;
let path = entry.path();
if kind.is_dir() {
if depth < args.max_depth {
// A folder we cannot read is reported and skipped, not fatal.
if let Err(e) = walk(&path, depth + 1, args, by_size) {
eprintln!("dupfind: skipping {}: {e}", path.display());
}
}
} else if kind.is_file() {
let size = entry.metadata()?.len();
if size >= args.min_size {
by_size.entry(size).or_default().push(path);
}
}
}
Ok(())
}
/// FNV-1a over the whole file, read 64 KiB at a time.
fn hash_file(path: &Path) -> io::Result<u64> {
let mut file = File::open(path)?;
let mut buf = [0u8; 64 * 1024];
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
loop {
let n = file.read(&mut buf)?;
if n == 0 {
return Ok(hash);
}
for &byte in &buf[..n] {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x0100_0000_01b3);
}
}
}
RSChange src/main.rs to run the search and print each group. It uses expect for now; the next steps replace that with proper errors:
cat > src/main.rs <<'RS'
mod cli;
mod scan;
use clap::Parser;
use cli::{Cli, Command};
fn main() {
let cli = Cli::parse();
let args = match &cli.command {
Command::Scan { common, .. } => common,
Command::Summary(common) => common,
};
let groups = scan::find_duplicates(args).expect("cannot read the folder");
for group in &groups {
println!("{} files, {} bytes each:", group.paths.len(), group.size);
for path in &group.paths {
println!(" {}", path.display());
}
println!();
}
}
RSMake a sample folder to search. It has a note copied three times (one copy has a Yoruba file name, to show that names in any script work), a draft with the same size as the note but different text, a random 4 KiB "photo" with a copy whose name has spaces, a copy in a hidden .cache folder, and two empty files:
mkdir -p sample/backup/2026 sample/.cache
printf 'ship on Friday\n' > sample/notes.txt
printf 'ship on Monday\n' > sample/draft.txt
cp sample/notes.txt sample/backup/notes-old.txt
cp sample/notes.txt sample/backup/2026/notes.txt
cp sample/notes.txt "sample/backup/àkọsílẹ̀.txt"
head -c 4096 /dev/urandom > sample/photo.jpg
cp sample/photo.jpg "sample/backup/photo (1).jpg"
cp sample/photo.jpg sample/.cache/photo.jpg
touch sample/empty.log sample/backup/empty.log
cargo run -q -- scan sampleCheck it worked
The output has two groups, the photo first because it is bigger:
2 files, 4096 bytes each:
sample/backup/photo (1).jpg
sample/photo.jpg
4 files, 15 bytes each:
sample/backup/2026/notes.txt
sample/backup/notes-old.txt
sample/backup/àkọsílẹ̀.txt
sample/notes.txtdraft.txt is missing because its bytes differ even though its size matches. The empty files are skipped by the default --min-size 1, and the copy in .cache is skipped because it is hidden.
Step 4 · Add output formats, a summary and environment settings
Replace src/main.rs with the full version. It matches on the subcommand, prints text, CSV or a summary, and writes through one locked handle to standard output instead of println!, so a write error becomes a value you can handle. The AppError type and the ExitCode return are explained in the next step.
cat > src/main.rs <<'RS'
mod cli;
mod scan;
use std::fmt;
use std::io::{self, Write};
use std::process::ExitCode;
use clap::Parser;
use cli::{Cli, Command, Format};
use scan::Group;
/// Exit code for "duplicates found" when --check is given.
const FOUND_DUPLICATES: u8 = 3;
/// The error main returns. Rust prints it as "Error: " followed by its
/// Debug form, so Debug prints the plain message.
struct AppError(String);
impl fmt::Debug for AppError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl From<io::Error> for AppError {
fn from(e: io::Error) -> Self {
AppError(format!("cannot write output: {e}"))
}
}
fn main() -> Result<ExitCode, AppError> {
let cli = Cli::parse();
let (args, output) = match &cli.command {
Command::Scan { common, output } => (common, Some(*output)),
Command::Summary(common) => (common, None),
};
let groups = scan::find_duplicates(args)
.map_err(|e| AppError(format!("cannot read {}: {e}", args.dir.display())))?;
let mut out = io::stdout().lock();
match output {
Some(Format::Text) => print_text(&mut out, &groups)?,
Some(Format::Csv) => print_csv(&mut out, &groups)?,
None => print_summary(&mut out, &groups)?,
}
out.flush()?;
if args.check && !groups.is_empty() {
Ok(ExitCode::from(FOUND_DUPLICATES))
} else {
Ok(ExitCode::SUCCESS)
}
}
fn print_text(out: &mut impl Write, groups: &[Group]) -> io::Result<()> {
if groups.is_empty() {
writeln!(out, "No duplicates found.")?;
}
for group in groups {
writeln!(out, "{} files, {} bytes each:", group.paths.len(), group.size)?;
for path in &group.paths {
writeln!(out, " {}", path.display())?;
}
writeln!(out)?;
}
Ok(())
}
fn print_csv(out: &mut impl Write, groups: &[Group]) -> io::Result<()> {
writeln!(out, "group,size,path")?;
for (i, group) in groups.iter().enumerate() {
for path in &group.paths {
// Quote every path and double any quote in it, so commas are safe.
let quoted = path.display().to_string().replace('"', "\"\"");
writeln!(out, "{},{},\"{}\"", i + 1, group.size, quoted)?;
}
}
Ok(())
}
fn print_summary(out: &mut impl Write, groups: &[Group]) -> io::Result<()> {
let extra: usize = groups.iter().map(|g| g.paths.len() - 1).sum();
let wasted: u64 = groups.iter().map(|g| g.size * (g.paths.len() as u64 - 1)).sum();
writeln!(out, "groups: {}", groups.len())?;
writeln!(out, "extra copies: {extra}")?;
writeln!(out, "wasted bytes: {wasted}")
}
RS
cargo run -q -- scan sample --output csvThe CSV has a header and one row per file, with the group number in the first column, so it opens cleanly in a spreadsheet or feeds awk. Now try the summary with different settings: the default, a shallower search, hidden files included, and a minimum size taken from the environment:
cargo run -q -- summary sample
cargo run -q -- summary sample --max-depth 2
cargo run -q -- summary sample --hidden
DUPFIND_MIN_SIZE=100 cargo run -q -- summary sample
DUPFIND_MIN_SIZE=100 cargo run -q -- summary sample --min-size 1An environment variable suits a setting you want every time, such as a minimum size in your shell profile, without typing it on each run. The command line still overrides it, as the last command shows.
Check it worked
The CSV output is:
group,size,path
1,4096,"sample/backup/photo (1).jpg"
1,4096,"sample/photo.jpg"
2,15,"sample/backup/2026/notes.txt"
2,15,"sample/backup/notes-old.txt"
2,15,"sample/backup/àkọsílẹ̀.txt"
2,15,"sample/notes.txt"The five summaries report:
- Default:
groups: 2,extra copies: 4,wasted bytes: 4141(one extra photo of 4,096 bytes and three extra notes of 15). --max-depth 2:extra copies: 3,wasted bytes: 4126, becausebackup/2026is three levels down.--hidden:extra copies: 5,wasted bytes: 8237, now counting the photo in.cache.DUPFIND_MIN_SIZE=100:groups: 1,wasted bytes: 4096, because the 15-byte notes fall below the minimum.- With
--min-size 1as well: back togroups: 2andwasted bytes: 4141.
Step 5 · Return exit codes a script can trust
A script cannot read your output, but it can read the exit code. dupfind now uses four:
0: it ran, and either found no duplicates or--checkwas not given.1: it could not do its job, for example the folder does not exist.2: the command line was wrong. clap prints the error and exits with 2 beforemaingets the arguments.3:--checkwas given and duplicates exist.
Two parts of main make this work. main returns Result<ExitCode, AppError>. On Ok, Rust exits with the ExitCode inside, which is how --check produces 3. On Err, Rust prints Error: ` followed by the error's `Debug form to standard error and exits with 1. A derived Debug would print AppError("...") with quotes and the type name, so AppError implements Debug by hand to print only the message. The ? after find_duplicates and after each print call returns early with that error.
Try each code:
cargo run -q -- scan sample --check > /dev/null || echo "exit code: $?"
cargo run -q -- scan no-such-folder || echo "exit code: $?"
cargo run -q -- scan sample --output xml || echo "exit code: $?"
cargo run -q -- scan sample/backup/2026 --check && echo "exit code: $?"In a shell script, the --check form fits in an if:
if ! dupfind scan ~/Pictures --check > /dev/null; then
echo "duplicates found, or dupfind failed"
fiCheck it worked
The four commands print, in order:
exit code: 3.Error: cannot read no-such-folder: No such file or directory (os error 2), thenexit code: 1.- An
invalid value 'xml'error listing[possible values: text, csv], thenexit code: 2. No duplicates found., thenexit code: 0, becausebackup/2026holds only one file.
Step 6 · Test the binary with assert_cmd
The checks you ran by hand belong in tests. assert_cmd builds your binary, runs it with the arguments and environment you give it, and checks the exit code and output. predicates supplies the matchers (contains, starts_with, not), and tempfile makes a fresh folder for each test that is deleted afterwards. Add all three as development dependencies, which are used by tests only and never end up in the binary:
cargo add --dev assert_cmd@2.2.2 predicates@3.1.4 tempfile@3.27.0Create tests/cli.rs. Cargo treats each file in tests/ as a separate test program that can only use your tool from the outside, the way a user does:
mkdir -p tests
cat > tests/cli.rs <<'RS'
use std::fs;
use assert_cmd::Command;
use predicates::prelude::*;
use tempfile::TempDir;
/// A folder with one pair of duplicates and one same-size file that differs.
fn sample() -> TempDir {
let dir = TempDir::new().unwrap();
fs::write(dir.path().join("a.txt"), "same text\n").unwrap();
fs::write(dir.path().join("b.txt"), "same text\n").unwrap();
fs::write(dir.path().join("c.txt"), "different\n").unwrap();
dir
}
fn dupfind() -> Command {
let mut cmd = Command::cargo_bin("dupfind").unwrap();
// Keep a value set in your own shell out of the tests.
cmd.env_remove("DUPFIND_MIN_SIZE");
cmd
}
#[test]
fn lists_the_duplicate_pair_only() {
let dir = sample();
dupfind()
.arg("scan")
.arg(dir.path())
.assert()
.success()
.stdout(predicate::str::contains("2 files, 10 bytes each:"))
.stdout(predicate::str::contains("a.txt"))
.stdout(predicate::str::contains("c.txt").not());
}
#[test]
fn csv_has_a_header_and_one_row_per_file() {
let dir = sample();
let assert = dupfind()
.args(["scan", "--output", "csv"])
.arg(dir.path())
.assert()
.success();
let text = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines[0], "group,size,path");
assert_eq!(lines.len(), 3);
}
#[test]
fn check_exits_with_3_when_duplicates_exist() {
let dir = sample();
dupfind().args(["scan", "--check"]).arg(dir.path()).assert().code(3);
}
#[test]
fn environment_sets_the_minimum_size() {
let dir = sample();
dupfind()
.env("DUPFIND_MIN_SIZE", "11")
.arg("summary")
.arg(dir.path())
.assert()
.success()
.stdout(predicate::str::contains("groups: 0"));
}
#[test]
fn depth_outside_the_range_is_a_usage_error() {
dupfind()
.args(["scan", "--max-depth", "0"])
.assert()
.code(2)
.stderr(predicate::str::contains("1..=64"));
}
#[test]
fn missing_folder_exits_with_1() {
dupfind()
.args(["scan", "no-such-folder"])
.assert()
.code(1)
.stderr(predicate::str::starts_with("Error: cannot read no-such-folder"));
}
RS
cargo testEach test builds its own sample, so the tests can run in parallel and in any order. The DUPFIND_MIN_SIZE=11 test works because both sample texts are 10 bytes.
Check it worked
cargo test ends with a line like test result: ok. 6 passed; 0 failed for tests/cli.rs. To see a failure, change code(3) to code(0) in check_exits_with_3_when_duplicates_exist and run cargo test again: the report shows the expected and actual exit codes. Change it back afterwards.
Step 7 · Build a small release binary
So far Cargo has built debug binaries: quick to compile, slow to run, and large. Build the release version and note its size:
cargo build --release
ls -lh target/release/dupfindThree settings in the release profile make it smaller. lto = true lets the optimiser work across your code and every crate at once and drop what is never called. codegen-units = 1 compiles each crate as one unit, which is slower to build but optimises better. strip = true removes the symbol table; Cargo's release profile already strips debug information by default. Add them to the end of Cargo.toml and rebuild:
cat >> Cargo.toml <<'TOML'
[profile.release]
lto = true
codegen-units = 1
strip = true
TOML
cargo build --release
ls -lh target/release/dupfindThe cost is a slower release build and backtraces without function names in the release binary. Debug builds and cargo test are unaffected.
Check it worked
The second ls -lh shows a smaller file than the first. Write both sizes down: on a laptop with little disk or a slow connection, the release binary is the whole program, with no runtime or interpreter to install beside it.
Step 8 · Install dupfind on your PATH
cargo install --path . builds the release profile and copies the binary to ~/.cargo/bin, which rustup put on your PATH when you installed Rust. --locked makes it use the exact versions in Cargo.lock:
cargo install --path . --locked
command -v dupfind
dupfind --version
dupfind summary sampleNow try it on a real folder of your own. It only reads, so this is safe:
dupfind summary ~/DownloadsWhen you change the code, run cargo install --path . --locked again to replace the installed copy.
Check it worked
command -v dupfind prints the installed path, usually ~/.cargo/bin/dupfind expanded to your home folder. dupfind --version prints dupfind 0.1.0, the version from Cargo.toml, and the summary matches the one from earlier: groups: 2, extra copies: 4, wasted bytes: 4141.
When you have finished, uninstall the tool and remove the practice project:
cargo uninstall dupfind
cd ~
rm -rf ~/dupfind-demoNext steps
- Handle errors in Rust with Result, ? and thiserror replaces the hand-written
AppErrorwiththiserrorandanyhow, so errors carry their cause and context. - Understand Rust ownership by fixing borrow checker errors explains the
&borrows thatfind_duplicatesand the print functions rely on. - Build a command-line tool in Swift on Linux builds a similar tool with swift-argument-parser, a useful comparison of how two languages approach the same job.
- To share
dupfindwith others, look atcargo build --release --targetfor other platforms, or publish it to crates.io so anyone can runcargo install dupfind.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials