Skip to content

Instantly share code, notes, and snippets.

@davidmoten
Last active September 3, 2019 08:56
Show Gist options
  • Save davidmoten/6618075 to your computer and use it in GitHub Desktop.
Save davidmoten/6618075 to your computer and use it in GitHub Desktop.
How to include a java class with main method in a bash script
#!/bin/bash
set -e
TEMPFILE=`mktemp /tmp/ScriptXXXXX|sed -e 's/\.//g'`
CLASS_NAME=`basename "$TEMPFILE"`
JAVA_SOURCE=$TEMPFILE.java
cat <<EOF >$JAVA_SOURCE.tmp
//Write your java class here with a main method
//Be sure to leave the name of the class as Script
public class Script {
public static void main(String[] args) {
System.out.println("Hello world");
for (String arg:args)
System.out.println("arg="+ arg);
}
}
EOF
## change the name of the class to match the file
sed "s/public class Script/public class $CLASS_NAME/g" $JAVA_SOURCE.tmp >$JAVA_SOURCE
## compile the java
javac $JAVA_SOURCE
## run the class using all passed in parameters from the command line
java -classpath /tmp $CLASS_NAME "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment