JBang - Java Command Line Tool Runner

JBang is a command-line tool that simplifies running Java code, scripts, and applications. Easily execute Java snippets, manage dependencies, and build CLI tools.

JBang

JBang is a versatile command-line tool that simplifies the execution of Java code, scripts, and applications. It allows developers to run Java snippets directly, manage dependencies seamlessly, and build command-line interfaces with ease. This tool streamlines the development workflow by abstracting away complex build configurations and setup processes.

JBang Command Line Application Examples

Below are common JBang commands for managing and running Java applications and scripts.

Creating and Editing Applications

# Create a new command line application using Picocli
jbang init --template=cli CmdLineApp.java

# Edit application with Visual Studio Code
jbang edit --open=code CmdLineApp.java

# Edit application with IDEA and have the project regenerated on dependencies changes
jbang edit --live --open=idea CmdLineApp.java

Building and Running Applications

# Rebuild application in cache without starting it
jbang build CmdLineApp.java

# Run command line application with jbang
jbang CmdLineApp.java command arg1 arg2...

# Run command line as a script
./CmdLineApp.java command arg1 arg2...

# Run a Java code snippet (Java 9 and later)
echo 'Files.list(Paths.get("/etc")).forEach(System.out::println);' | jbang -

Debugging and Remote Execution

# Debugging a command line application
jbang --debug CmdLineApp.java command arg1
# Then start debugger in IDEA once port is printed

# Run a script from the network
jbang https://github.com/jbangdev/jbang-catalog/blob/master/hello.java

# Run a jbang script referenced in a catalog
# Where hello.java is located in jbang-catalog repository of GitHub jbangdev user
jbang hello@jbangdev

# Run a jar file from its GAV (Group:Artifact:Version)
jbang io.swagger:swagger-codegen-cli:RELEASE --help

JDK Management and Cache Operations

# Install a specific JDK version to be used with jbang
jbang jdk install 14

# Force usage of a specific JDK version in a jbang script
## Add //JAVA 14 to the first lines of the script
## Then start it using jbang

# List all jbang installed JDKs
jbang jdk list

# Clear jbang cache to remove temporary files and downloaded dependencies
jbang cache clear

Shell Auto-completion

# Install auto-completion script for Bash
jbang completion | sudo tee /etc/bash_completion.d/jbang

JBang Benefits and Use Cases

JBang is invaluable for developers who need a quick and efficient way to execute Java code without the overhead of traditional build tools. It supports running single Java files, scripts with dependencies, and even JAR files directly from the command line. This makes it ideal for scripting, rapid prototyping, and creating small, self-contained Java utilities.

External Resources