In Bash this would be ${0##*/}
.
use std::env;
use std::path::Path;
fn prog() -> String {
let prog = env::args().next().unwrap();
String::from(Path::new(&prog).file_name().unwrap().to_str().unwrap())
}
fn main() {
println!("{}", prog());
}
Is there a better way? (I particularly dislike those numerous unwrap()
s.)
If you don't care about why you can't get the program name, you can handle all the potential errors with a judicious mix of map
and and_then
. Additionally, return an Option
to indicate possible failure:
use std::env;
use std::path::Path;
use std::ffi::OsStr;
fn prog() -> Option<String> {
env::args().next()
.as_ref()
.map(Path::new)
.and_then(Path::file_name)
.and_then(OsStr::to_str)
.map(String::from)
}
fn main() {
println!("{:?}", prog());
}
If you wanted to follow delnan's awesome suggestion to use std::env::current_exe
(which I just learned about!), replace env::args().next()
with env::current_exe().ok()
.
If you do want to know why you can't get the program name (and knowing why is usually the first step to fixing a problem), then check out ker's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With