1

From the answer to How do I invoke a system command in Rust and capture its output?, I can execute a command which itself spawns a shell to execute commands.

use std::process::Command;

Command::new("sh")
    .spawn()
    .expect("sh command failed to start");

Is it possible to execute commands from Rust in this newly gained shell?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Harshit
  • 39
  • 3
  • 1
    Shells just take commands as stdin and generates output on stdout. So in theory all you need to do is capture stdin/stdout and interact with those (write to stdin and read from stdout). It's generally a pain in the ass because of blocking & buffering & friends though, which is why tools like expect/pexpect exist to take care of all the fiddly bits. – Masklinn Sep 09 '20 at 08:35

1 Answers1

3
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()?;

Source: External Command in The Rust Cookbook.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Null Mastermind
  • 1,038
  • 10
  • 8