Skip to content

Instantly share code, notes, and snippets.

@eggplants
Last active February 16, 2022 21:09
Show Gist options
  • Save eggplants/c859fe6424c34fb0106a8a5274932f69 to your computer and use it in GitHub Desktop.
Save eggplants/c859fe6424c34fb0106a8a5274932f69 to your computer and use it in GitHub Desktop.
Convert Jar with dependencies generated by `mvn package assembly:single` into shell script
#!/usr/bin/env bash
main() {
set -euxo pipefail
local USAGE JSONNAME SHNAME
readonly USAGE="usage: $0 <jar-with-dependencies>"
readonly JSONNAME="${1-}"
readonly SHNAME="${JSONNAME%jar}sh"
if ! command -v file &>/dev/null; then
echo 'install: file'>&2
return 1
elif [ $# -ne 1 ]; then
echo "$USAGE" >&2
return 1
elif ! { [ -n "$JSONNAME" ] && [ -f "$JSONNAME" ];}; then
echo "not found: '$JSONNAME'" >&2
echo "$USAGE" >&2
return 1
elif ! [[ "$(file "$JSONNAME")" =~ ^.*jar:[[:space:]]Zip[[:space:]]archive[[:space:]]data.*$ ]]; then
echo "invalid file: '$JSONNAME'"
echo "$USAGE" >&2
return 1
fi
cat<<'A'>"$SHNAME";cat "$JSONNAME">>"$SHNAME";chmod +x "$SHNAME"
#!/bin/sh
if ! command -v sed java&>/dev/null; then echo install: sed java>&2;exit 1;fi
t="`mktemp`"
sed 1,5d "$0">"$t";java -jar "$t";rm "$t"
exit $?
A
}
main "${@}"
exit $?
@eggplants
Copy link
Author

# convert jar into sh
$ ./jar2sh target/testj-1.0.jar

# execute jar as sh locally
$ ./testj-1.0.jar.sh

# install globally
$ sudo install testj-1.0.jar.sh /usr/local/bin/testj

# execute jar as sh globally
$ testj

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment