Skip to content

Instantly share code, notes, and snippets.

@isurfer21
Created July 19, 2024 03:16
Show Gist options
  • Save isurfer21/421b5ca7b7116cfd31e7f3e7faba0211 to your computer and use it in GitHub Desktop.
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
#!/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"
@isurfer21
Copy link
Author

You can save this script to a file (e.g., rust.sh or rust), make it executable with chmod +x rust, then keep it somewhere globally accessible, and finally run it with rust <rust_filename>.

@isurfer21
Copy link
Author

Let me explain how the script works:

  1. The script checks if no arguments are provided, and if so, shows an error message and the help menu.
  2. The script then loops through the command-line arguments. If the -h or --help flag is provided, it shows the help menu and exits.
  3. Otherwise, it assumes the first argument is the Rust filename and stores it in the RUST_FILENAME variable.
  4. The script checks if the file exists, and if not, shows an error message and exits.
  5. The script compiles the Rust file using rustc. If the compilation fails, it shows an error message and exits.
  6. If the compilation succeeds, the script runs the generated binary using ./<binary_name>.
  7. 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