Run Java directly in Shebang Scripts

With the introduction of JEP 330 in Java 11, it is possible to run a Java program directly from a single source code file without having to compile it first.

To run a Java program using JEP 330, you can use the following shebang line in your shell script:

#!/usr/bin/java --source 11

Where "/usr/bin/java" is the location of the java command (you can figure this out with which java).

This tells the operating system to use java to interpret the script, and the --source 11 option specifies the Java version that the code is written in.

#!/usr/bin/java --source 11

public class FooBar {
    public static void main(String[] args) {
        System.out.println("https://www.DEVLABS.ninja");
    }
}

In this example, the Java code is contained in a single file named myscript.sh (and not FooBar.java like the conventional naming dictates), and the main method simply prints out a message to the console.

Note that you'll need to make the shell script executable with: chmod +x myscript.sh, and then you can run it with ./myscript.sh.

Unfortunately, the definition of the class FooBar with the main method cannot be skipped, so this adds some boilerplate code to the script. The name of the class is of course freely selectable.

Classpath Entries

We can also add entries to the classpath like for a regular Java application:

#!/usr/bin/java -classpath /Users/devlabs/.m2/repository/commons-lang/commons-lang/2.6/* --source 11

public class FooBar {
    public static void main(String[] args) {
        System.out.println("https://www.DEVLABS.ninja");
        System.out.println(org.apache.commons.lang.StringUtils.reverse("https://www.DEVLABS.ninja"));
    }
}

In this example the StringUtils class is used in the script after adding the commons-lang library to the classpath.