r/programminghorror • u/Xor_Boole • 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
./hellowill produce the output "Hello, World!". Java will ignore the shebang when parsing the jar, until it hits the zip header.
Wat.
0
Upvotes
45
u/wung Jul 04 '15 edited Jul 04 '15
That's not a java thing, but rather just your
shellprogram 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: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.