shellrustcommand-linecommand

How to pipe commands in rust?


I am trying to execute a command in a shell and get the return value as a string. The command I'm trying to execute is ps axww | grep mongod | grep -v grep.

I've seen solutions over the internet, but they don't explain the code, so it is hard customising it to my needs.

example: how to do a sandwich pipe in rust? & Pipe between two child processes

Can someone please provide a solution and go line by line explaining how it works in layman's terms.


Solution

  • What you need is the documentation, where they do explain everything line by line, with thorough examples. Adapted from it, here is your code

    use std::process::{Command, Stdio};
    use std::str;
    
    fn main() {
        let ps_child = Command::new("ps") // `ps` command...
            .arg("axww")                  // with argument `axww`...
            .stdout(Stdio::piped())       // of which we will pipe the output.
            .spawn()                      // Once configured, we actually
                                          // spawn the command...
            .unwrap();                    // and assert everything went right.
        let grep_child_one = Command::new("grep")
            .arg("mongod")
            .stdin(Stdio::from(ps_child.stdout.unwrap())) // Pipe through.
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        let grep_child_two = Command::new("grep")
            .arg("-v")
            .arg("grep")
            .stdin(Stdio::from(grep_child_one.stdout.unwrap()))
            .stdout(Stdio::piped())
            .spawn()
            .unwrap();
        let output = grep_child_two.wait_with_output().unwrap();
        let result = str::from_utf8(&output.stdout).unwrap();
        println!("{}", result);
    }
    

    See the playground (which of course won't output anything since there is no process called mongod running...).