To be clear, by executable I do not mean literal bytes ready for the processor. For example a bash script, which is interpreted and not executable, becomes executable when a shebang is added to the top that specifies the script should be run by /bin/bash
or /bin/sh
or whatever program will be interpreting it.
I was wondering if it's possible to do with Java, which is not technically a scripting language but is definitely not executable. It seems like Java would be hard because the user doesn't actually have the opportunity to add a shebang to the compiled file, and the compiled java cannot come from stdin.
After two and a half years I have stumbled upon a more complete answer than was given in 2016. The Java binaries can be embedded within the executable, contrary to John Hascall's answer. This article explains how this can be done in linux and unix like systems by adding a binary payload to a shell script.
I will offer a short summary of the procedure.
Given an executable jar named any_java_executable.jar
Given you want to create an executable named my_executable
Given a script file named basis.sh
with the following contents
#!/bin/sh
MYSELF=`which "$0" 2>/dev/null`
[ $? -gt 0 -a -f "$0" ] && MYSELF="./$0"
java=java
if test -n "$JAVA_HOME"; then
java="$JAVA_HOME/bin/java"
fi
exec "$java" $java_args -jar $MYSELF "$@"
exit 1
The native executable can be created by running the following two commands.
cat basis.sh any_java_executable.jar > my_executable;
chmod +x my_executable;
Then my_executable
is a native executable capable of running the java program without depending on the location of the jar file. It can be executed by running
./my_executable [arg1 [arg2 [arg3...]]]
and can be used anywhere as a CLI tool if placed in /usr/local/bin
.