Command-line tools are a great way to automate tasks, process data, or even just have fun with small utilities. Rust is an excellent language for this because it compiles to fast, standalone binaries with no runtime dependency and offers strong safety guarantees.
In this article, we’ll walk through building a simple CLI tool in Rust that reads a file and counts the number of words—similar to the Unix wc
command.
Step 1: Set Up Your Project
Start by creating a new binary project:
cargo new wordcount --bin
cd wordcount
This gives you a working Rust project with src/main.rs
as your entry point.
Step 2: Parse Command-Line Arguments
To keep things simple, we'll use the built-in std::env
module to fetch the file path from the command line:
use std::env;
use std::fs;
fn main() {
let args: Vec = env::args().collect();
if args.len() < 2 {
eprintln!("Usage: wordcount ");
std::process::exit(1);
}
let filename = &args[1];
let contents = fs::read_to_string(filename)
.expect("Something went wrong reading the file");
let word_count = contents.split_whitespace().count();
println!("Word count: {}", word_count);
}
Step 3: Build and Test It
Build the project:
cargo build --release
Try it out:
./target/release/wordcount sample.txt
If everything works, you should see the number of words printed to the terminal.
Use Case Scenario
Imagine you're managing hundreds of text-based logs generated daily by a data pipeline. Manually reviewing them is inefficient. A fast CLI tool like this one can help you quickly analyze the logs—perhaps to find the lengthiest reports, flag empty files, or identify unusually verbose entries. With minimal setup, you can extend the tool to scan directories, summarize data, or even integrate into shell scripts. The result is better visibility into your data with significantly reduced manual effort—saving both time and cognitive load in your workflow.
✅ Pros and ❌ Cons of Using Rust for CLI Tools
✅ Pros:
- ⚡ Blazing fast binaries
- 🧼 Memory safety without garbage collection
- 📦 Great ecosystem with crates like
clap
,serde
, andanyhow
- 🧪 Easy to write tests and CI integration
❌ Cons:
- 📘 Steep learning curve for beginners
- ⏱ Compile times can get long on larger projects
- 🧱 Advanced tasks (like TUI or async IO) require extra learning
Summary
You’ve just built your first real CLI tool in Rust! While this example is simple, it demonstrates core concepts: parsing input, reading files, and producing useful output. Rust's type system, safety, and performance make it a compelling choice for building CLI tools of any size.
Want to go further? I’ve written a concise, 15-page PDF guide that walks you through crafting professional tools from start to finish—including input parsing, formatting, file handling, and distribution:
Crafting Command-Line Tools in Rust: A Practical Guide to Building Fast, Reliable Utilities — just $5.
If this was helpful, you can also support me here: Buy Me a Coffee ☕
Top comments (0)