Macro sh::cmd

source ·
cmd!() { /* proc-macro */ }
Expand description

A command-running macro.

cmd is a macro for running external commands. It provides functionality to pipe the input and output to/from variables as well as using rust expressions as arguments to the program.

The format of a cmd call is like so:

cmd!( [prog] [arg]* [< {inexpr}]? [> {outexpr}]? [;]? )

Or you can create multiple commands on a single block

cmd! {
  [prog] [arg]* [< {inexpr}]? [> {outexpr}]? ;
  [prog] [arg]* [< {inexpr}]? [> {outexpr}]? ;
  [prog] [arg]* [< {inexpr}]? [> {outexpr}]? [;]?
}

Arguments are allowed to take the form of identifiers (i.e. plain text), literals (numbers, quoted strings, characters, etc.), or rust expressions delimited by braces.

This macro doesn’t execute the commands. It returns an iterator of sh::QCmd which can be executed. Alternatively, see sh::sh which executes the commands sequentially.

§Examples

let world = "world";
let mut out = String::new();
cmd!(echo hello {world} > {&mut out}).for_each(|cmd| cmd.exec().unwrap());
assert_eq!(out, "hello world\n");
cmd! {
  echo hello;
  sleep 5;
  echo world;
}.for_each(|cmd| cmd.exec().unwrap()); // prints hello, waits 5 seconds, prints world.

You can also use string literals as needed

let mut out = String::new();
cmd!(echo "hello world" > {&mut out}).for_each(|cmd| cmd.exec().unwrap());
assert_eq!(out, "hello world\n");