How to build a self-executable jar file

I'm always looking for ways to simplify the management of Java services. Recently, I've learned how to create a self-executing jar file without the need for an extra bash script.

Create a main class. For this post, the ubiquitous Hello World:

public class HelloWorld {
	public static void main(String[] args) {
		System.out.println("Hello World");
	}
}

Create a manifest file which defines your main class:

echo Main-Class: HelloWorld > MANIFEST.MF

Next, compile your class(es):

javac HelloWorld.java

Assemble a jar file:

java -cvmf MANIFEST.MF hello.jar HelloWorld.class

Create a small bash script to execute the jar (stub.sh):

#!/usr/bin/java -jar

You can optionally also include JAVA_OPTS in this bash script:

#!/usr/bin/java -Xms256m -Xmx512m -jar

Finally, munge the bash script and jar together into a new file:

cat stub.sh hello.jar > hello.sh

Make the file executable:

chmod +x hello.sh

Now you can execute the file:

./hello.sh