[Solved] Piped in Process Command Does not Work

Hi,
I used find to find file and do more actions with the result. However the piped doesn't work as I would expected.
The command is essentially: find . -type f | grep api
This is the snippet of my code:

let find_command = Command::new("find")
      .current_dir(target_folder_path)
      .stdout(Stdio::piped())
      .args( &[".", "-type", "f"])
      .output()
      .expect("Error occurred in find.");

      io::stdout().write_all(&find_command.stdout).unwrap();
      io::stderr().write_all(&find_command.stderr).unwrap();
    
      let grep_command = Command::new("grep")
      .stdin(Stdio::piped())
      .arg("api")
      .output()
      .expect("Error occurred in grep.");

      io::stdout().write_all(&grep_command.stdout).unwrap();
      io::stderr().write_all(&grep_command.stderr).unwrap();

The find is correctly shown in the io, but grep doesn't show anything where it suppose to be.

How do I fix this?

Thank you for replying in advance.

Solution:
The correct way to pipe the code above:

let find_command = Command::new("find")
      .current_dir(target_folder_path)
      .stdout(Stdio::piped())
      .args( &[".", "-type", "f"])
      .output()
      .expect("Error occurred in find.");

      io::stdout().write_all(&find_command.stdout).unwrap();
      io::stderr().write_all(&find_command.stderr).unwrap();
    
      let grep_command = Command::new("grep")
// Changed here
      .stdin(Stdio::from(find_command.stdout.expect("Failed to open echo stdout")))

      .arg("api")
      .output()
      .expect("Error occurred in grep.");

      io::stdout().write_all(&grep_command.stdout).unwrap();
      io::stderr().write_all(&grep_command.stderr).unwrap();

More details about handling I/O: std::process - Rust

You are not piping anything into grep.

1 Like

Thank you again. I thought the .stdout(Stdio::piped()) in the first command specify the output will be going to piped.
Then .stdin(Stdio::piped()) will collect the piped output from the first command.
But this is not the case. I found the correct way to pipe it:

let find_command = Command::new("find")
      .current_dir(target_folder_path)
      .stdout(Stdio::piped())
      .args( &[".", "-type", "f"])
      .output()
      .expect("Error occurred in find.");

      io::stdout().write_all(&find_command.stdout).unwrap();
      io::stderr().write_all(&find_command.stderr).unwrap();
    
      let grep_command = Command::new("grep")
      .stdin(Stdio::from(find_command.stdout.expect("Failed to open echo stdout")))
      .arg("api")
      .output()
      .expect("Error occurred in grep.");

      io::stdout().write_all(&grep_command.stdout).unwrap();
      io::stderr().write_all(&grep_command.stderr).unwrap();
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.