Skip to content

Instantly share code, notes, and snippets.

@thingsiplay
Last active December 1, 2021 15:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thingsiplay/381b9c45345bef547ee7ca979022cbd5 to your computer and use it in GitHub Desktop.
Save thingsiplay/381b9c45345bef547ee7ca979022cbd5 to your computer and use it in GitHub Desktop.
Run Rust source code like a script
#!/bin/sh
# rscript: Rust script interpreter
# Shebang in rust.rscript: #!/usr/bin/env -S rscript 2018
# Directory where compiled binaries are saved to.
# Example: /var/tmp/rscript or /tmp
output_dir=/var/tmp/rscript
# -C panic=abort
# abort, unwind
panic=abort
# -C opt-level=0
# 0=no+debug, 1=basic, 2=some, 3=all, s=size, z=size+off loop vect.
optlevel=1
# --cap-lints allow
# allow, warn, deny, forbid
caplints=allow
edition=$1
input=$(realpath $2)
output=$output_dir/$(basename $input)
md5file=$output.md5
mkdir -p "$output_dir"
if [ -e $md5file ]
then
md5sum --status --check "$md5file"
Result=$?
else
Result=1
fi
if [ $Result -ne 0 ]
then
md5sum "$input" > "$md5file"
rustc --edition $edition -C opt-level=$optlevel -C panic=$panic --cap-lints $caplints -o "$output" "$input"
fi
shift 2
"$output" $@
#!/usr/bin/env -S rscript 2018
// rust.rscript: Rust template
// vim: ft=rust
fn main() {
let w = "World!";
println!("Hello {}", w);
}
@thingsiplay
Copy link
Author

thingsiplay commented Apr 11, 2021

So, if you are like me and just want to play and experiment a little bit and move on, then try this out. You write a regular Rust code and just put a Shebang on top of it, like a shell script. It points to another "real" shell script to invoke the compiler and run the temporary created executable. That is basically all. Its hilarious, because the compiler is known to be slow and the language is very strict. But for the Memes! I have even created a template with the "rust.rscript" in my templates folder. Have fun.

  • rscript - Shell script to compile and run the Rust source code
  • rust.rscript - Rust source code template with a Shebang

Off course the "rscript" interpreter needs to be in the $PATH in this case. Example folders are "~/local/bin" or "/usr/local/bin" to save the "rscript" Rust script interpreter to, in order to be found by the "rust.rscript".

Edit: Now edition must be specified as first argument to the interpreter. Other options are not supported. Also a compiled script file with the same name as one in another directory could have a conflict. Have this in mind.

Here is an alternative way of achieving something similar: https://www.reddit.com/r/rust/comments/monzuc/run_rust_source_code_like_a_script_linux/gu54l0r/?utm_source=reddit&utm_medium=web2x&context=3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment