shell-exec
This is a crate that simplifies the execution of CLI programs from Rust programs using a macro exec!(error_id, cmd). The error_id is just a unique string literal that is printed in the case of an error. I typically generate this string literal as follows:
and pasting the output in the as the first argument of exec!. This simplifies finding the right code snipped in case you need to track down the code that issued a certain error message.
On success, exec! returns the stdout of the executed command. If the execution fails, the macro retuns an Err of type ShellError. One can handle the errors using the question mark operator:
exec!`
The cmd argument is a format sting, i.e., one can use positional and named arguments as well as variable names:
let path="/tmp";
exec!`
As for macro format!, macro exec! supports positional arguments:
// example: with position argument "/"
println!;
exec! also supports named arguments:
// example: with named argument p="/tmp"
println!;
Hence, prints on stderr an error message that includes:
-
the command line that failed,
-
the error ID,
-
the stdout,
-
the stderr,
-
the cargo information related to this
Example
Here is a simple program that uses this crate:
#!/usr/bin/env rust-script
//! ```cargo
//! [package]
//! name = "example"
//! edition = "2024"
//!
//! [dependencies]
//! clap = { version = "4", features = ["derive"] }
//! shell-exec = { version = "*", path = "/home/ubuntu/subtree-sconectl/check_cpufeatures/shell-exec" }
//! colored = "*"
//! ```
use *;