0

Following the question at How to execute a command in a shell running as a child process?, I want to execute multiple commands.

let mut child = Command::new("sh").stdin(Stdio::piped())
    .stderr(Stdio::piped())
    .stdout(Stdio::piped())
    .spawn()?;

child.stdin
    .as_mut()
    .ok_or("Child process stdin has not been captured!")?
    .write_all(b"something...")?;

let output = child.wait_with_output()?;

Is it possible to do something like this?

.write_all(b"something...")?
.write_all(b"something...")?;
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Harshit
  • 39
  • 3

2 Answers2

1

This is not a problem in Rust, but sh. In sh you need to separate commands by newlines ("\n"):

//...
.write_all(b"command1\ncommand2")?;
//...

this should work too:

//...
let child_stdin = child.stdin
    .as_mut()
    .ok_or("Child process stdin has not been captured!")?;

child_stdin.write_all(b"command1\n")?;
child_stdin.write_all(b"command2\n")?;
//...
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
chpio
  • 896
  • 6
  • 16
0

Chaining method calls works for methods that, by convention, return self or &mut self. There is no guarantee that all methods do that, some simply have more useful return values. For example, write_all() returns Result<(), io::Error>, declaring that it has no useful value other than showing whether the writing succeeded or failed.

To call such a method twice, you need to save your value into a local variable:

let child_stdin = child
    .stdin
    .as_mut()
    .ok_or("Child process stdin has not been captured!")?;
child_stdin.write_all(b"something...")?;
child_stdin.write_all(b"something...")?;
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user4815162342
  • 141,790
  • 18
  • 296
  • 355