Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I invoke a system command and capture its output?

Tags:

rust

People also ask

How do you execute a command and save the output to a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

How do you capture output of a command in a variable in a shell script?

Here are the different ways to store the output of a command in shell script. You can also use these commands on terminal to store command outputs in shell variables. variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name=`command` variable_name=`command [option ...]


std::process::Command allows for that.

There are multiple ways to spawn a child process and execute an arbitrary command on the machine:

  • spawn — runs the program and returns a value with details
  • output — runs the program and returns the output
  • status — runs the program and returns the exit code

One simple example from the docs:

use std::process::Command;

Command::new("ls")
        .arg("-l")
        .arg("-a")
        .spawn()
        .expect("ls command failed to start");

a very clear example from the docs:

use std::process::Command;
let output = Command::new("/bin/cat")
                     .arg("file.txt")
                     .output()
                     .expect("failed to execute process");

println!("status: {}", output.status);
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("stderr: {}", String::from_utf8_lossy(&output.stderr));

assert!(output.status.success());

It is indeed possible! The relevant module is std::run.

let mut options = std::run::ProcessOptions::new();
let process = std::run::Process::new("ls", &[your, arguments], options);

ProcessOptions’ standard file descriptors default to None (create a new pipe), so you can just use process.output() (for example) to read from its output.

If you want to run the command and get all its output after it’s done, there’s wait_with_output for that.

Process::new, as of yesterday, returns an Option<Process> instead of a Process, by the way.