How to cleanly get the path to the bash history?

2019-09-06 12:23发布

问题:

So, now and then i am looking into Rust, and this time i have the simple task to get the path to my bash history file. So, you come up with env::var() and env::home_dir() and like to join them. Now, it's like 1 or 2 lines in python and probably in C, i came up with this hideous 3 liner:

let h_file = env::var("HISTFILE").unwrap_or(OsString::from_string(".bash_history".to_string())).into_string().unwrap_or_else(|_| { panic!("the end is near!!!")});
let h_dir = env::home_dir().unwrap_or_else(|| { panic!("unable to get homedir!") } );
let h_file_p = h_dir.join(h_file);

What would be the better way? To be honest, i am concerned that, as a beginner, just using the docs, i came up with is this hideous thing.

Edit: Of course the point is that the first line is that long, and i am aware that i could put all those commands in several lines following each other or use a gazillion match statements, all of which would not really make this a nice solution for a basic task..

回答1:

I think you are suffering because of the transition between std::old_path and std::path, namely on the return value of home_dir(). Once it returns a std::path::PathBuf, it will look like:

#![feature(os,env,path)]

use std::env;
use std::ffi::OsString;
use std::path::PathBuf;

fn future_home_dir() -> Option<PathBuf> {
    Some(PathBuf::new("/home/user"))
}

fn main() {
    let filename = env::var_os("HISTFILE").unwrap_or(OsString::from_str(".bash_history"));
    let home_dir = future_home_dir().expect("could not determine a home directory");
    let path = home_dir.join(&filename);

    println!("{:?}", path);
}

The stable version of this is:

use std::env;
use std::ffi::OsString;

fn main() {
    let filename = env::var_os("HISTFILE").unwrap_or_else(|| OsString::from(".bash_history"));
    let home_dir = env::home_dir().expect("could not determine a home directory");
    let path = home_dir.join(&filename);

    println!("{:?}", path);
}


标签: rust