run_shell - shell script written in rust.
run_shell is a helper library for std::process::Command to write shell script like tasks in rust. The library only works with unix-like operation systems.
Run command
extern crate run_shell;
use *;
// Run command by cmd! macro
cmd!.run.unwrap;
// Contain white space or non-alphabetical characters
cmd!.run.unwrap;
// Pass an argument
let name = "run_shell";
cmd!.run.unwrap;
// Extract environment variable
cmd!.run.unwrap;
ShellResult
The return value of ShellCommand#run()
is ShellResult
which is Ok(_)
only
when the command successfully runs and its execution code is 0, so you can use
?
operator to check if the command successfully exits or not.
extern crate run_shell;
use *;
Output string
ShellCommand has a shorthand to obtain stdout as UTF8 string.
extern crate run_shell;
use *;
assert_eq!;
Spawn
ShellCommand has spawn()
method which runs the command asynchronously and
returns ShellChild
.
extern crate run_shell;
use *;
extern crate libc;
// Wait
let child = cmd!.spawn.unwrap;
child.wait.unwrap;
// Signal
let child = cmd!.spawn.unwrap;
let result = child.wait;
assert!;
Thread
If you would like to run a sequence of commands asynchronously, shell::spawn
creates a thread as well as std::thread::spawn
but it returns ShellHandle
wrapping std::thread::JoinHandle
.
ShellHandle#signal()
is used to send a signal to processes running on the
thread. It also stops launching a new process by ShellComamnd::run()
on that
thread.
extern crate run_shell;
use *;
extern crate libc;
let handle = spawn;
let result = handle.join.unwrap;
assert!;
Signal handling
trap_signal_and_wait_children()
starts watching SIGINT and SIGTERM, and waits
all child processes before exiting the process when receiving these signals. The
function needs to be called before launching any new thread.
extern crate run_shell;
use *;
trap_signal_and_wait_children.unwrap;
Access underlaying objects
ShellComamnd
wraps std::process::Command
and ShellChild
wraps
std::process::Child
. Both underlaying objects are accessible via public
fields.
extern crate run_shell;
use *;
use Stdio;
use Read;
// Access std::process::Command.
let mut shell_command = cmd!;
// Access std::process::Child.
let shell_child = shell_command.spawn.unwrap;
shell_child.wait.unwrap;