Java for Shell Scripting

Yes, you read the title right.

Brian Schlining
2 min readDec 29, 2023

--

Photo by Cookie the Pom on Unsplash

Medium served up the article, Revisiting Java for Shell Scripting, in my feed. Since I frequently use the JVM for scripting (mostly using scala-cli), I took the author’s suggestions for a spin. In brief, this was what was proposed in the article:

#!/usr/bin/env -S java --source 21 --enable-preview

void main() {
System.out.println("Hello, World!")
}

To run this, do the following:

  1. Save to a file Test1.java
  2. Run chmod u+x Test1.java
  3. Run ./Test1.java

This works! However, there are two problems with this approach. First, the shebang line is not normal Java code, and will generally freak out your code editor. Second, you can’t pass command line arguments to the Java program this way.

Below is an alternative, using /// instead of #!. I tested this in a variety of shells on a Mac and it worked fine, but be warned that using /// may not work on all systems.

///usr/bin/env -S java --source 21 --enable-preview "$0" "$@" ; exit $?

void main(String[] args) {
var name = args.length > 0 ? args[0] : "World";
System.out.println(STR."Hello, \{name}");
}

Now my code editor is happy and I can pass arguments to my program:

> ./Test2.java Brian

Hello, Brian

While this approach is suitable for simple scripts, for those requiring external dependencies, consider exploring:

These tools enable your scripts to seamlessly fetch and utilize third-party libraries, expanding their capabilities.

--

--

Brian Schlining

Polyglot coder. Deep-sea Researcher. Zazen aficionado. I think squids are pretty cool.