Search code examples
rustcdworking-directory

Why isn't my Rust code cding into the said directory?


use std::{
    env, io,
    path::PathBuf,
    process::{self, Command},
};

fn inner_main() -> io::Result<PathBuf> {
    let exe = env::current_exe()?;
    let dir = exe.parent().expect("Executable must be in some directory");
    let dir = dir.join("nvs");
    Ok(dir)
}

fn main() {
    let path = inner_main().expect("Couldn't get path.");
    let path = path.into_os_string().into_string().unwrap();
    Command::new("cd")
        .arg(&path)
        .status()
        .expect("Something went wrong.");
    process::exit(0);
}

I grab the path that the binary is in, go into the parent directory so the binaries name is no longer in the path and then append "nvs" at the end of the path and then in main() I put the inner_main() function in a let and then redeclare the let as a string so I can cd into the directory.

Whenever it tries CDing into the nvs directory nothing happens and I know that the command runs because if I move the binary somewhere with no nvs file in it's same directory it runs saying it can't find that directory so my question is when it's in a directory with nvs why doesn't it actually cd into the said directory like it should?


Solution

  • You're attempting to run an external command called cd. Depending on your operating system, this either fails because there is no command called cd, or this does nothing other than test whether the directory exists and you have permission to access it. If a cd command exists, it runs in a subprocess of your program, and its change of directory does not affect your process.

    To change to a different directory, you need to change the working directory of your own process. Call std::env::set_current_dir.

    std::env::set_current_dir(&path).expect("Unable to change into [path to executable]/nvs");
    // do stuff in …/nvs