0

I'm writing a command-line tool using Rust. I want to cd to the wanted dictionary when I execute my Rust command-line tool.

I use env::set_current_dir(path), but it does not work. After that, I use nix, call nix::unistd::chdir(path), but it does not work either.

So how can I archieve the goal of chaging command dictionary? How to make cd call in Rust.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Parker
  • 3
  • 1
  • 3
  • [This](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=4bfe741abba33777e2a6686c95bf80ed) seems to work. Are you expecting it to change the working directory in the shell executing the Rust program? – kmdreko Oct 31 '20 at 02:30
  • 2
    _No_ program can change the directory of the software that called it -- not written any any language, not just Rust. You can't write a shell script that changes the directory of the shell that called it either, unless you source it into your parent shell instead of executing it as a separate process. – Charles Duffy Oct 31 '20 at 03:13
  • 3
    I propose [How to change directory in terminal from a C file](https://stackoverflow.com/questions/31896927/how-to-change-directory-in-terminal-from-a-c-file) as a duplicate. The answer is "you can't", for the exact same reason you can't do it from Rust, or Python, or Java, or assembly, or any other language. – Charles Duffy Oct 31 '20 at 03:14
  • @kmdreko Yes. I want to change the shell working directory When I execute Rust command-line tool. You code can only change Rust runtime's working directory but has no affect on shell working directory. – Parker Oct 31 '20 at 16:22

1 Answers1

3

This is not directly possible - the Rust program can only affect its own environment, not your shell. You can define a shell function which uses the output of your Rust program to perform some action, for example

# bash
mycd() {
    cd "$(command myrustprogram)"
}
// main.rs
fn main() {
    println!("/some/path")
}
ephemient
  • 198,619
  • 38
  • 280
  • 391
  • Does this mean I have to make two commands? One is installed using `cargo install` from my Rust project to calculate my wanted directory path. Another is bash shell script to call the Rust command. – Parker Oct 31 '20 at 16:27
  • @Parker Depends on what you mean by "shell script". If it's another executable, it still won't work - it needs to be a script that's sourced by the shell (e.g. a snippet in `~/.bashrc`). You can generate the snippet from your Rust program and tell the user to add `eval "$(myrustprogram init bash)"` to their `~/.bashrc` (or whatever arguments cause your program to emit the correct shell snippet). See https://starship.rs/ for an example of this. – ephemient Oct 31 '20 at 18:09