Skip to content

Instantly share code, notes, and snippets.

@richardjwild
Last active March 27, 2024 13:17
An example of a Java program that can be executed as a shell script.
#!/usr/bin/java --source 17
public class EchoArguments {
public static void main(String[] args) {
System.out.printf("Arguments: %s%n", String.join(", ", args));
}
}
@richardjwild
Copy link
Author

richardjwild commented Mar 27, 2024

This ability has existed since Java 11, although this script utilises some Java 17 features as well.

Three requisites:

  1. The file must be executable, i.e: chmod u+x java-shell-script
  2. The filename must not have a .java extension. (This caught me out for some time).
  3. The file may contain multiple classes. Precisely one of them must have a static main method with the usual signature.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment