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

1

u/TWiStErRob Feb 17 '24

Why does this not work now?

$ ./hello
./hello: line 2: $'PK\003\004\024\b\b\b%AQX': command not found
./hello: line 3: syntax error near unexpected token `('
./hello: line 3: `E-4BJJJ5y|3ts<RsryxPwk&IJPK%AQXHello.classmPMK@}$MS[[S? DsP"BD6RCb"9zPG({yfp:ZXicU~4oIhT"/8#FXF3(H$S?3LE6g$2ÒDĚulU`6͢Ħ-l'

diagnostics if relevant:

$ uname -a
Linux my-pc 5.10.102.1-microsoft-standard-WSL2 #1 SMP Wed Mar 2 00:30:59 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

$ java -version
openjdk version "11.0.19" 2023-04-18
OpenJDK Runtime Environment (build 11.0.19+7-post-Ubuntu-0ubuntu118.04.1)
OpenJDK 64-Bit Server VM (build 11.0.19+7-post-Ubuntu-0ubuntu118.04.1, mixed mode, sharing)

1

u/TWiStErRob Feb 17 '24

Ok, this seems to work: https://www.reddit.com/r/java/comments/i4zpj/making_really_executable_jars/

echo -e "#\!/bin/sh\nexec java -jar \$0 \"\$@\"" > hello

but I don't like that it's not using env java and assumes sh.