this post was submitted on 22 Oct 2024
-3 points (38.5% liked)

Rust Programming

8176 readers
1 users here now

founded 5 years ago
MODERATORS
 

I would like to share a bash script I made for when you want to simply run a rust script once and delete it. Instead of having compile the script with rustc, running the binary and then deleting the binary, you can achive all of this with this bash script below.

The first argument will be the rust script file name. The .rs file extension is optional. The rest of the arguments are passed into the executed binary.

Simply name the bash script to something like rust-run.sh.

#!/bin/bash

#Get file path from first parameter
path=$(dirname "$1")

#Get file name from first parameter
fileName=$(basename "$1")
fileName="${fileName%'.rs'}"

#Compile executable and save it in the same directory as the rust script
rustc "${path}/${fileName}.rs" -o "${path}/${fileName}"

#If rustc commands retuned any errors, unable to compile the rust script
if [ $? -ne 0 ]; then
    return
fi

#Execute compilled executable and pass the rest of the parameters into the executable
"${path}/${fileName}" ${*:2}

#Delete compillled executable
rm "${path}/${fileName}"

If someone wants to rewrite this in rust or add these features into the rustc, feel free to do so.

top 2 comments
sorted by: hot top controversial new old
[โ€“] ElectricMoose 4 points 1 month ago* (last edited 1 month ago)

Allow me to retort with an all-in-one self build script, along with pass-through args and exitcode.

#!/bin/sh
out=$(mktemp)
sed -e '0,/^#SELFBUILD$/d' "$0" | rustc --o "$out" - && "$out" "$@"
status=$?
rm -f "$out"
exit "$status"
#SELFBUILD

fn main() {
    dbg!(std::env::args());
    println!("hello rust");
    std::process::exit(2);
}

P.S. I have no idea why you'd want that, as it's a terribly inefficient way to ship code, but it's a fascinating glimpse at how we used to do self-extract archives decades ago.

[โ€“] [email protected] 1 points 3 weeks ago

@trymeout you'd probably want to use cargo script: https://rust-lang.github.io/rfcs/3424-cargo-script.html

It's already available on nightly