How to get a shell condition is true or false in rust

Viewed 65

I found std::process in document. But it seems that it cannot work. For example:

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

    let command = Command::new("command")
        .arg("-sq")
        .arg("ls")
        .spawn()
        .unwrap();
    println!("{command:#?}");
}

Output:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }', 1.rs:8:10
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

But run the command in shell:

$ command -sq ls && echo true || echo false
true

So how can I get a output like shell in rust?

1 Answers

The most direct equivalent would be this:

let command = Command::new("fish")
    .args(["-c", "command -sq ls"])
    .output()
    .unwrap();

if command.status.success() {
    println!("true");
} else {
    println!("false");
}

This creates a fish shell which then executes your command command. The .success() method can be used to infer if the command succeeded or failed same as && and || in your script.

Related