Skip to content

Scripting in java with Jbang

Posted on:August 19, 2022 at 01:00 PM

Intro

Scripting in java, that sounds pretty strange, right? I have to admit it too until I start working with JBang for minimal command line tools.

The journey is not straight forward as bash script (#! /bin/bash script) where assumption specific libraries, tools, other user’s scripts and environment variables are available to consume. The trade off for that hardness is an opening gate to vast ecosystem of java libraries which are widely used in my projects. That’s amazing !!! For me, as a long time Java user, I think I now can be extremely productive in making scripts, reusing them my projects. Here are a few notes for using JBang.

The good parts

The not so good parts

Alright, this is not a silver bullet to solve all problems without any hiccup. Here are few things I’ve learnt along with my experiment with JBang.

You still really need IDE so as to be productive.

User experience to build a script is acceptable but building a scripting ecosystem around JBang is quite an open journey. I’ve learnt it the hard way where I restructured my project many times. For an example, this part is for common classes and that part need to be a separate directory. This mean if you really want to invest in JBang scripting, you may build and break stuffs a few times before you get the click! on your project.

Some of Java API is quite alienated ones since I rarely use them. You will fell the verbose side of java on this. Some times, to achieve a simple task, you need to write a few line codes while comparing to python or bash, it is only one line. The struggle of Dependency Injection (DI) container for certain libraries. Simply do I miss the magic of DI here. Most of projects I have been through, DI container just saves days of effort if we manually hand crafted code. I wish JBang someday support DI out of the box. That would be a game changer for java scripting for sure.

To make CLI tools, I have to learn picocli library. That’s a burden on learning curl. For an example, to handle options and parameters, I get it straight with getops from bash script but now, all the stuff become Java class fields with annotation on them.

Interact with OS native tools is not straight forward as in bash script.

I will come back JBang again with hand-on public repository in near future but in the mean times, if you are Java user and want to a sip of it for scripting task, have it a shot and I bet you feel pretty comfortable and productive in a few hours. Jumping to below home page and cli reference will kick-start you quite a lot.

P/S: install IntelliJ Jbang plugin at the beginning will save you a lot of time.

References