2

I want a way to print the command with its arguments. In my real case, those arguments are generated and I want to see the command that we're going to run.

I'm trying to do this:

fn main() {
    use std::process::Command;

    let x = Command::new("sh").arg("2");

    let y = x.output();

    println!("status: {:#?}", x);
    println!("status: {:#?}", y);
}
error[E0597]: borrowed value does not live long enough
  --> src/main.rs:4:13
   |
4  |     let x = Command::new("sh").arg("2");
   |             ^^^^^^^^^^^^^^^^^^         - temporary value dropped here while still borrowed
   |             |
   |             temporary value does not live long enough
...
10 | }
   | - temporary value needs to live until here
   |
   = note: consider using a `let` binding to increase its lifetime

I can get it to work if I don't add the .arg("2") above, but that doesn't help me with my usecase.

All the other examples on stackoverflow doesn't seem to help me solving this.

Razze
  • 4,124
  • 3
  • 16
  • 23

1 Answers1

3

Command::arg takes self by mutable reference, so you need to store the Command returned by Command::new in a variable before calling arg, otherwise the Command would be dropped at the end of the statement. (The compiler could in theory use a hidden variable here as it does in other circumstances, but it doesn't do it as of Rust 1.29.)

fn main() {
    use std::process::Command;

    let mut x = Command::new("sh");
    x.arg("2");

    let y = x.output();

    println!("status: {:#?}", x);
    println!("status: {:#?}", y);
}
Francis Gagné
  • 60,274
  • 7
  • 180
  • 155