Java 11 shebang example in Docker : In Java 11, JEP 330 adds support to run single-file source code directly.

Terminal :

# Before Java 11
$ javac Hello.java
$ java Hello

# Now Java 11
$ java Hello.java

This indirectly supports the Java single-file program to run as a script using Unix Shebang. For example, run below .sh file will print Hello World!

run.sh :

#!/opt/java/openjdk/bin/java --source 11
public class SheBang {

    public static void main(String[] args) {

        System.out.println("Hello World!");

    }
}

Make sure the !# is pointed to the correct java.

Test in Docker

Since I don’t have Linux on hands, so this example will test on Windows, using Docker image adoptopenjdk/openjdk11:alpine.

Lire aussi : Example of Java SSLSocket TLS 1.3

This example runs a Java program as a shell script, using run.sh file. Read comments for self-explanatory.

Windows

# This is Windows command prompt

# first run, it will take some time to download the image
# run alpine with openjdk11 installed, and start shell sh
> docker run -it adoptopenjdk/openjdk11:alpine sh

# done, enter the shell automatically
/ #

# make sure Java installed
/ # java -version
openjdk version "11.0.7" 2020-04-14
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.7+10)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.7+10, mixed mode)

# find out where is java
/ # which java
/opt/java/openjdk/bin/java

/ # nano
sh: nano: not found

# we need an editor, apk install nano
/ # apk add nano

/ # nano run.sh

put this in run.sh

#!/opt/java/openjdk/bin/java --source 11
public class SheBang {

    public static void main(String[] args) {

        System.out.println("Hello World!");

    }
}

Windows

# still inside container
# assign execute permission
/ # chmod +x run.sh

# run it, done.
/ # ./run.sh
Hello World!

# bye
/ # exit

References

Laisser un commentaire