Crate rsbash

source ·
Expand description

rsbash: run bash commands from rust.

Our macros rash! and rashf! allow you to call out to a bash shell, just as you would typically from a terminal. Since this is accomplished by interacting with libc, these macros can only be used on unix-like platforms (Linux, macOS etc).

Motivation

Making a shell command with the native std::process::Command builder is quite involved.

Suppose you wanted to write “Hello world!” to stdout.

 use std::io::Write;
 use std::process::Command;

 let command = Command::new("echo")
               .arg("Hello world!")
               .output()
               .expect("Uh oh, couldn't say hello!");
 std::io::stdout().write_all(&command.stdout).unwrap();

 assert_eq!(std::str::from_utf8(&command.stdout).unwrap(), "Hello world!\n");

Now suppose you wanted to pipe the output to a second command, and then write the result to stdout:

use std::process::{Command, Stdio};
use std::io::Write;

let echo = Command::new("echo")
           .arg("Hello world!")
		   .stdout(Stdio::piped())
		   .spawn()
		   .expect("Uh oh, couldn't say hello!");
					   
let grep = Command::new("grep")
           .arg("Hello")
           .stdin(Stdio::from(echo.stdout.unwrap()))
           .output()
           .expect("Uh oh, couldn't grep for Hello!");
    
std::io::stdout().write_all(&grep.stdout).unwrap();

assert_eq!(std::str::from_utf8(&grep.stdout).unwrap(), "Hello world!\n");

With rash! the same command is as simple as:

 use rsbash::rash;

 let (ret_val, stdout, stderr) = rash!("echo 'Hello world!' | grep 'Hello'").unwrap();
 assert_eq!(stdout, "Hello world!\n");

See the rash! and rashf! macros, and the RashError for more information.

Macros

  • Run a bash command.
  • Format and run a bash command.

Enums

  • The error thrown if something went wrong in the processing of the command.