5

I'm trying to replicate the cd command in Rust, just for learning.

But the problem is that I'm not sure how to change a directory in the OS (*nix). I have tried with:

std::process::Command::new("cd")
    .arg(path) //path is a String
    .spawn()
    .expect("Directory failed");

And also tried with:

let path = Path::new(path_str.as_str());
let changed_dir = env::set_current_dir(&path).is_ok();

And changed_dir is true.

Even I tried changing env::set_var("PWD", path) but nothing seems to work.

I checked this part of the documentation: https://doc.rust-lang.org/std/env/fn.set_current_dir.html but I think is just for a type of sandboxed path or directory.

Any more ideas?

Sierisimo
  • 639
  • 8
  • 21
  • How do you check if it works? – kennytm Apr 12 '17 at 05:44
  • Well... my process is still on learning but I run: `cargo build` and then executes: `./target/debug/rcd FULL_PATH` where FULL_PATH is the destiny (almost all time I check with my home). My first runs used a hardcoded string, now I'm using `clap` to parse arguments. – Sierisimo Apr 12 '17 at 05:46
  • 8
    It's not possible to change the external terminal's $PWD. Not in Rust, not in C, not in any language. See http://stackoverflow.com/questions/4884681/how-to-use-cd-command-using-java-runtime for an explanation. It is only possible as a shell function like http://stackoverflow.com/questions/874452/change-current-directory-from-a-script – kennytm Apr 12 '17 at 05:53
  • Thanks, that's useful information, I have to read deeper, because I saw https://github.com/gsamokovarov/jump to work with, I assume that tool just creates it's own enviroment. – Sierisimo Apr 12 '17 at 06:00
  • 4
    It defines a shell function called `j` in https://github.com/gsamokovarov/jump/blob/fca01f577dde1b379e2b2023233182e5c6b88911/shell/bash.go#L19-L22, i.e. the method in the second related link. The `j` function runs the main Go program to compute the target directory, then invoke the built-in `cd` to jump to there. – kennytm Apr 12 '17 at 06:05
  • 3
    @Shepmaster how is this a duplicate of questions for other languages? – asymmetric Sep 11 '17 at 18:50
  • 1
    @asymmetric because the problem has nothing to do with the implementation language. Check out [the comment that currently has 5 votes](https://stackoverflow.com/questions/43361154/how-to-change-os-to-directory-using-rust?noredirect=1#comment73784627_43361154) which already explains that, then check out the [comment with 4 votes](https://stackoverflow.com/questions/43361154/how-to-change-os-to-directory-using-rust?noredirect=1#comment73784972_43361154) which explains how you can use a program to compute a directory to navigate to with the shell's `cd` command instead. – Shepmaster Sep 11 '17 at 19:15
  • Sure, but that comment should've actually been an (accepted) answer. – asymmetric Sep 11 '17 at 20:34

0 Answers0