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

45

u/wung Jul 04 '15 edited Jul 04 '15

That's not a java thing, but rather just your shell program loader. If you start something with ./, it will try to figure out how to. It will figure out how to execute the program by checking out the header. If it begins with an elf-header, it will start the binary. If it starts with a shebang, it will start it using the given command, passing the file to it:

~ $ echo "#! $(which echo) hello" > tmp
~ $ cat tmp
#! /bin/echo hello
~ $ chmod +x tmp
~ $ ./tmp
hello ./tmp

The fact that java does not crash with the shebang there, comes from the way zip files are made: the header is at the end of the file.

13

u/sysop073 Jul 04 '15

The shell doesn't handle shebangs, it's the loader