Find an Executable
Find a binary on the PATH
Locating an executable means walking each directory on the PATH. It also means
applying the platform’s rules. On Windows that includes the PATHEXT extensions
such as .exe. The which crate does exactly what a shell does. It hands back
the absolute path of the first match.
which resolves a single best match. which_all yields every match in
precedence order. That helps when a name is shadowed by more than one install. A
name that is not on the PATH comes back as an Error. A caller handles a
missing tool with ? or a match rather than a panic.
use which::{which, which_all};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cargo = which("cargo")?;
println!("cargo resolves to {}", cargo.display());
assert!(cargo.is_absolute());
for path in which_all("cargo")? {
println!("candidate: {}", path.display());
}
match which("definitely-not-a-real-binary") {
Ok(path) => println!("found at {}", path.display()),
Err(error) => println!("not on PATH: {error}"),
}
Ok(())
}