Writing "shell scripts" with rust

Hi! I've been interested in rust for awhile, but I haven't really had too many reasons to use it yet. One thing that I was interested in trying was rewriting some of my personal shell scripts in rust. I've seen several crates for args parsing, but are there any good tools for doing common shell tasks like copying, moving, symlinking, generating files, etc...? Or are these things that should be done with the std lib? Is Rust a bit too low level for something like this? Are there any good examples out there of similar bins?

Any help is appreciated! Thanks!

We write a fair bit of scripty code using Rust and it works just fine. For example, the new build system is mostly about moving files around and running programs, and is written in Rust.

std contains most of the stuff you need for basic scripting, but you might also want the walkdir crate. If you use windows you'll also eventually be bitten by the remove_dir_all bug (it's really hard to remove directories reliably on windows). Both cargo and rustup have hand-rolled versions of remove_dir_all to deal with it.

3 Likes

Also, rust source code supports shebangs, so you should be able to use something like cargo-script to run cargoified source code directly.

3 Likes

If you want to be very scripty, an option is to use std::process to invoke cp, mv, ln et. al.

But you can save some overhead by using standard library functions. Look in std::fs and std::os::your_os::fs (in particular the symlink function in std::fs is deprecated in favor of os specific functions).

2 Likes

Do you have a link to the new build system? Might be a bit over my head, but I'd still be interested in browsing the code.

edit Ahh, found this, is this the newest version? https://github.com/rust-lang/rust/tree/master/src/bootstrap/build

@webdesserts yes that's it

There is duct which I didn't try but that looks very nice.

Dang, I've just implemented walkdir. This is why hanging out here is so useful. But, yes, Rust is totally suitable for small programs that need to be robust. 0.5s build time is not much to pay for something sold and well-checked.

Check https://crates.io/crates/cmd_lib it contains common rust commandline macros and utilities, to write shell-script like tasks in a clean, natural and rusty way.