Created
April 25, 2019 12:01
-
-
Save srishanbhattarai/ce49a9ee65c60ac466cdaedf5801294d to your computer and use it in GitHub Desktop.
Check if a file exists in $PATH in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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