cargo rust build script - print output of command

Viewed 2816

I am new to rust and cargo, and I am trying to do something very simple!

I have something like this (in build.rs):

use std::process::Command;

fn main() {
    Command::new("echo 123");
}

And I want to see the output of the command echo 123. I want 123 to get printed to the build output (this is mostly to debug what I am doing) and wont be part of the final project.

I have tried cargo build --verbose - this does not work.

I can't extrapolate an answer from there posts (and some others like it):

I feel this must be simple to do - but I have been stuck for hours looking on the web and not finding the answer.

1 Answers

Just building a Command with Command::new does not execute it yet. It just starts a builder pattern. To actually execute it, you have to use the methods spawn, output or status. Example:

Command::new("echo")
    .arg("123")
    .spawn()
    .expect("failed to spawn process");

It's very unfortunate that this doesn't produce a warning. Someone recently tried to add the #[must_use] attribute to Command, which would make your code procude a warning. The PR closed for now but it seems like it will be added eventually.

Related