r/programminghorror • • Jul 04 '15

Yes, Java supports shebangs.

Let Hello.java be the following:

public class Hello {
    public static void main(String... args) {
        System.out.println("Hello, World!");
    }
}

Then, running the following shell commands:

javac Hello.java
jar -cfe Hello.jar Hello Hello.class
echo "#\!/usr/bin/env java -jar" > hello
cat Hello.jar >> hello
chmod +x hello
./hello

will produce the output "Hello, World!". Java will ignore the shebang when parsing the jar, until it hits the zip header.

Wat.

0 Upvotes

15 comments sorted by

View all comments

6

u/suspiciously_calm Jul 05 '15

AFAIK the zip "header" is actually a zip "footer" with negative pointers from the end of the file, so the prepended sheband doesn't interfere with the package contents.

2

u/mck1117 Jul 05 '15

Just like in windows how you can put a WinPE header and a little bit of code at the beginning of a JAR to make it executable as an EXE.