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

2

u/sysop073 Jul 04 '15

If Java actually had anything to do with ignoring the shebang, I would call that a useful feature; why would that be bad? The syntax is chosen because # is a comment in lots of languages, but for programs that would otherwise choke on that line it's nice of them to special case it so shebangs will still work

6

u/kageurufu Jul 05 '15

Its really that zip file headers are not required to start the file.

cat image.jpg file.zip > hiddenzip.jpg

It will open in a zip program, but look like a jpg.

I have a huge folder of book cover images that have ebooks stored this way

4

u/sysop073 Jul 05 '15

I believe you, but I don't think it has anything to do with what I said. I said that if OP's understanding were true and Java were actually ignoring that shebang, that doesn't seem like a "programming horror", it seems like a pretty useful thing for them to have implemented. It ended up not even being right, but I disagree with the post either way; that'd be a pretty useful feature in my opinion

2

u/Pokechu22 Jul 06 '15

OK, that's amazing.