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!;
Macro s! is similar to macro exec! but it uses crate log to issue output (instead of eprintln!).
Hence, it does not have a flag verbose. Moreover, it logs the command at info level,
logs the output at debug level, and errors at error level.
Example:
// s! the command is executed and the output is returned
// s! uses the logger to print the command if the log level is set to info
// s! uses the logger to print the output of the command if the log level is set to debug
s!?;
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. Note that you need to define dependency colored.
#!/usr/bin/env rust-script
//! ```cargo
//! [package]
//! name = "example"
//! edition = "2024"
//!
//! [dependencies]
//! clap = { version = "4", features = ["derive"] }
//! sh-exec = "*"
//! colored = "*"
//! ```
use *;
Executing the code as a rust-script (see file example.rs), we get the following output:
)
)
)
)
)