Created
July 19, 2024 03:16
-
-
Save isurfer21/421b5ca7b7116cfd31e7f3e7faba0211 to your computer and use it in GitHub Desktop.
A bash script expects rust filename then compiles, executes & deletes binary to automate the process
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
HELP_MENU="Usage: ${0##*/} [-h|--help] <rust_filename> | |
Compile and run a Rust file, then delete the binary. | |
Options: | |
-h, --help Show this help menu | |
" | |
if [ $# -eq 0 ]; then | |
echo "Error: Rust filename is required" | |
echo "$HELP_MENU" | |
exit 1 | |
fi | |
while [ $# -gt 0 ]; do | |
case "$1" in | |
-h|--help) | |
echo "$HELP_MENU" | |
exit 0 | |
;; | |
*) | |
RUST_FILENAME="$1" | |
;; | |
esac | |
shift | |
done | |
if [ ! -f "$RUST_FILENAME" ]; then | |
echo "Error: File '$RUST_FILENAME' does not exist" | |
exit 1 | |
fi | |
rustc "$RUST_FILENAME" | |
if [ $? -ne 0 ]; then | |
echo "Error: Compilation failed" | |
exit 1 | |
fi | |
BIN_FILENAME="${RUST_FILENAME%.rs}" | |
./"$BIN_FILENAME" | |
rm "$BIN_FILENAME" |
Let me explain how the script works:
- The script checks if no arguments are provided, and if so, shows an error message and the help menu.
- The script then loops through the command-line arguments. If the
-h
or--help
flag is provided, it shows the help menu and exits. - Otherwise, it assumes the first argument is the Rust filename and stores it in the
RUST_FILENAME
variable. - The script checks if the file exists, and if not, shows an error message and exits.
- The script compiles the Rust file using
rustc
. If the compilation fails, it shows an error message and exits. - If the compilation succeeds, the script runs the generated binary using
./<binary_name>
. - Finally, the script deletes the binary using
rm
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can save this script to a file (e.g.,
rust.sh
orrust
), make it executable withchmod +x rust
, then keep it somewhere globally accessible, and finally run it withrust <rust_filename>
.