Skip to content

Instantly share code, notes, and snippets.

@srishanbhattarai
Created April 25, 2019 12:01
Show Gist options
  • Save srishanbhattarai/ce49a9ee65c60ac466cdaedf5801294d to your computer and use it in GitHub Desktop.
Save srishanbhattarai/ce49a9ee65c60ac466cdaedf5801294d to your computer and use it in GitHub Desktop.
Check if a file exists in $PATH in Rust
// look_path returns a boolean indicating if the binary can be found in $PATH.
fn look_path(path: &str) -> Result<bool, std::env::VarError> {
std::env::var("PATH").and_then(|paths| {
Ok(paths
.split(":")
.map(|p| format!("{}/{}", p, path))
.any(|p| Path::new(&p).exists()))
})
}
fn main() {
match look_path("echo") {
Ok(found) => {
if found {
// found
} else {
// not found
}
}
Err(err) => {
// handle error
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment