Scripting with JBang instead of Python
developmentI recently needed to write some scripts to automate some updates to Microservices.IO.
I normally write scripts in Python (or perhaps bash
, if they simple) since it’s easy to use and has lots of handy libraries.
But this time I decided to try JBang, which is a tool that let’s you write scripts in Java.
Installing JBang
First, I installed JBang using SDKMAN!:
$ sdk install jbang
Creating a JBang script
Second, I created the script:
$ jbang init Example.java
This command creates the executable file Example.java
.
$ ./Example.java
[jbang] Building jar...
Hello World
Here are the contents:
///usr/bin/env jbang "$0" "$@" ; exit $?
import static java.lang.System.*;
public class Example {
public static void main(String... args) {
out.println("Hello World");
}
}
Editing a JBang script in your IDE
Next, I then edited this script in IntelliJ IDEA:
$ jbang edit --open=idea Example.java
This command creates IntelliJ IDEA project that has a symbolic link to Example.java
.
Adding dependencies
The scripts, which process Markdown files, mainly used classes from java.nio.file.*
and java.util.regex.*
.
However, one script generated Markdown files using Thymeleaf templates.
It was remarkably easy to add the Thymeleaf dependency using the DEPS
directive:
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS org.thymeleaf:thymeleaf:3.1.1.RELEASE
After rerunning, jbang edit
to update the IntelliJ IDEA project, I could write the Thymeleaf code.
Summary
JBang makes it easy to write scripts using Java, which is statically typed and has sophisticated IDEs. But before feeling entirely comfortable with using JBang instead of Python, there are a couple of things I to do: