"cd" has no effect when executing series of commands

Viewed 53

I want to make a small CLI kinda project where I can execute series of commands. So, I wrote this code:

let commands = ["cd C:\\Users\\MegaMind\\Documents\\dynamodb_local_latest","dir","echo rust"];
for ccc in &commands {
    let rc = Command::new("cmd")
        .arg("/C")
        .arg(ccc)
        .output()
        .expect("there was an error");

    io::stdout().write_all(&rc.stdout).unwrap();
    // io::stdout().write_all(&rc.stderr).unwrap();
}

It seems like it runs the dir command within the source code's folder instead of C:\\Users\\MegaMind\\Documents\\dynamodb_local_latest. How can I get the cd to take effect?

1 Answers

The working directory applies on a per-process basis. Each Command is a separate process. The cd command changes the working directory for that process, and then that process exits and the record of that directory change is gone. Then you launch a new process (the one running dir) and it's still using the original working directory.

If you want to set the working directory for any given child command, just use the current_dir method when setting it up or (depending on what your needs are) you may want to change the Rust process's working directory (which will be inherited by child processes when not overridden).

Related