Skip to content

Instantly share code, notes, and snippets.

@plar
Last active January 11, 2023 18:17
Show Gist options
  • Save plar/d559f3bec5779f05bd69dc4b3aa61b0f to your computer and use it in GitHub Desktop.
Save plar/d559f3bec5779f05bd69dc4b3aa61b0f to your computer and use it in GitHub Desktop.
Make Java JAR file self executable in linux

How to make a java jar file to be a single file executable?

Create JAR File

# javac hello/main.java 
# jar cfme hello_world.jar Manifest.txt hello.Main hello/main.class

Create java self executable shell script

# cat stub.sh hello_world.jar > hello_world.sh
# chmod u+x hello_world.sh
# ./hello_world.sh
Hello world
# 
// create it in the `hello` directory (hello/main.java)
package hello;
public class Main
{
public static void main(String[] args)
{
System.out.println("Hello world");
}
}
Manifest-version: 1.0
Created-By: 1.0 (https://github.com/plar)
Main-Class: hello.Main
#!/bin/sh
# extract script name
MYSELF=`which "$0" 2>/dev/null`
[ $? -gt 0 -a -f "$0" ] && MYSELF="./$0"
# setup java
java=java
if [ -n "$JAVA_HOME" ]; then
java="$JAVA_HOME/bin/java"
fi
# extract jar from the script
jar_file=$(mktemp /tmp/java_app.XXXXX.jar)
START_JAR_LINENO=$(grep -a -m 1 -n -E "^###EOF###$" $MYSELF | cut -d':' -f1)
tail -n +$(($START_JAR_LINENO+1)) $MYSELF > $jar_file
# check if extracted jar exists and the jar file is not empty
if [ -s $jar_file ]; then
# ... yeah, run it
"$java" $java_args -jar $jar_file "$@" "- $BASH_LINENO -"
# delete temp jar file and exit
rm -rf $jar_file
else
# ... oops
echo "No jar attached!"
fi
exit 1
# EOF is a special marker
# We will append JAR after the EOF marker and extract it to a temporary file
# It is also important to keep an empty extra line after the marker
###EOF###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment