this post was submitted on 22 Oct 2024
13 points (84.2% liked)

Rust

5999 readers
23 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

!performance@programming.dev

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 1 year 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.

you are viewing a single comment's thread
view the rest of the comments
[–] nous@programming.dev 12 points 3 weeks ago (2 children)

You might want to checkout rust-script which essentially does the same but also lets you use it as a hashbang line to make executable rust scripts. And works with cargo/can install deps.

There is also an RFC for this feature.

[–] onlinepersona@programming.dev 0 points 4 days ago* (last edited 4 days ago)

That's pretty cool, but terrifying as well. Can't wait for somebody to go a step further and start writing proc macros (call it rusht) to replace bash scripts with rust scripts. Actually, now that I think about it, not so terrifying. They can probably be debugged better, could be safer (unless someone starts publishing malicious proc macros), allow dependencies to be added to compose better scripts without relying on they system's package manager, and so much more.

Anti Commercial-AI license

[–] trymeout@lemmy.world 0 points 3 weeks ago

Thank for sharing rust-script which is basically what I made but written in Rust and seems to store the binary in another directory when the binary is exexuted.

Is the RFC trying to introduce a command cargo script to run single rust scripts?