Rust for shell scripting experiences request


#1

Hi,

I have a bunch of shell scripts in bash which build packages by calling, configure, make, make test, do some string matching, etc. I am considering rewriting these to make them more maintainable and easier to extend. However, historically I have done this rewriting using Python but would like to give Rust a try.

I wonder if there are people out there that have done this and want to share their experience. If not, I does anybody have any pointers on where to start looking at the documentation? How to call a shell command, pass arguments, get stdout and stderr and maybe pipe them to yet another command?

Thanks.


#2

For running commands and looking at their output, start with the std::process module:

https://doc.rust-lang.org/nightly/std/process/struct.Command.html

The docs have some good examples.


#3

Calling on a shell script (as long as it has the proper shebang) from within rust is about as easy as calling any other executable as a sub process. To do so I would recommend familiarizing yourself with the Command and Stdio structs in the std::process module.

The Command struct will let you set up any executable with arguments, environment variables, etc., as well as run it and capture its output and other related functions.

The Stdio opaque type will let you configure a subprocess’ std{in, out, err} by either allowing the parent process to pass data to/from the child, letting the child inherit the same stdio handles, or make them the equivalent of /dev/null.

Setting up pipes between to child processes (e.g. if you want something like foo | bar | baz as a shell command) will require you to create your own pipes (via libc's pipe function) and convert the raw OS file descriptors/handles into Stdios appropriately.

Since piping things yourself gets messy, you can always invoke some shell from your rust program and have it actually execute the commands, but do be careful if you have to pass any input as arguments to them and avoid any sensitization problems from untrusted input.