#!/bin/bash
declare headertype="gui"
#if being used as a generic launcher jar is not set, if a jar is wrapped set jar="0",ifusedasalaunch0"
declare errtitle="You must install Java Runtime Environment !"
declare downloadurl=""
declare supporturl=""
declare cmdline
declare chdir
declare priority="normal"
#var format is "export name1=value1;export name2=value2" if value contains spaces it must be quoted eg "spaced value"
declare var
declare mainclass
#cp is a colon(:) separated list of glob patterns
declare cp
declare path
declare minversion="1.6.0"
declare maxversion
declare jdkpreference="preferJre"
declare initialheapsize
declare initialheappercent
declare maxheapsize
declare maxheappercent
#opt format is a space separated list of options to pass to java, options that contain spaces must be quoted eg "option with space"
declare opt
#declare startuperr="An error occurred while starting the application."
declare bundledjreerr="This application was configured to use a bundled Java Runtime Environment but the runtime is missing or corrupted."
declare jreversionerr="This application requires a Java Runtime Environment."
#declare launchererr="The registry refers to a nonexistent Java Runtime Environment installation or the runtime is corrupted."
#constants for comparison
declare -r console=console
declare -r gui=gui
declare -r jreonly=jreOnly
declare -r preferjre=preferJre
declare -r preferjdk=preferJdk
declare -r jdkonly=jdkOnly
declare -r normal=normal
declare -r idle=idle
declare -r high=high
#if this script is edited do not change anything above this line
#set to true to disable prompts to run updatedb
declare nolocateerror
#by default returns 0 for jre, 1 for jdk
#if jdkpreference equals preferjdk returns 0 for jdk, 1 for jre
#returns 2 for unspecified
jtype () {
declare jre={1/jre/}
declare jdk=1/jdk/if[["jre" != "1" && "jdk" = "1"]]thenif[[−njdkpreference && "jdkpreference"="preferjdk" ]]
then
return 1
else
return 0
fi
fi
if [[ "jdk"!="1" ]]
then
if [[ -n jdkpreference && "jdkpreference" = "$preferjdk" ]]
then
return 0
else
return 1
fi
fi
return 2
}
checkextra () {
declare jv="1"declarehd={jv/-/}
declare -i jve=0
if [[ "hd"!="jv" ]]
then
jv={jv%%-*}\_
jve=1
else
jv=jv_
fi
echo "jv"returnjve
}
extractvn () {
declare vn
if [[ x"1"!=x""]]thendeclaret={1%%.*}
if [[ x"t"=x"1" ]]
then
t={1%%_*}
fi
t={t##0}
vn="t"elsevn=0fiecho"vn"
return 0
}
extractrvn () {
declare nsn={1#*.}
if [[ x"nsn" = x"1"]]thennsn={sn1#*_}
fi
echo "$nsn"
return 0
}
#returns zero if both args are equal, 1 if 1ishigherthan2 and 2 if 1islowerthan2
compare () {
declare jv1=(checkextra"1")
declare -i jve1=?declarejv2=(checkextra "2")declare−ijve2=?
declare sn1="jv1"declaresn2="jv2"
if [[ x"sn1"!=x"sn2" ]]
then
while [[ x"sn1"!=x""∣∣x"sn2" != x"" ]]
do
declare -i vn1=(extractvn"sn1")
declare -i vn2=(extractvn"sn2")
if [[ vn1−gtvn2 ]]
then
return 1
fi
if [[ vn1−ltvn2 ]]
then
return 2
fi
sn1=(extractrvn"sn1")
sn2=(extractrvn"sn2")
done
fi
if [[ jve1−ltjve2 ]]
then
return 1
fi
if [[ jve1−gtjve2 ]]
then
return 2
fi
#compare jre and jdk
if [[ -z 3∣∣−z4 ]]
then
return 0
fi
jtype 3declare−ijt1=?
jtype 4declare−ijt2=?
if [[ jt1−ltjt2 ]]
then
return 1
fi
if [[ jt1−gtjt2 ]]
then
return 2
fi
return 0
}
#two parameters fixed and percentage higher value is returned
getheapmem () {
declare -i heapsize=1if[[−n2 ]]
then
#change 4to2 to get total memory
declare -i mem=(free -m | grep Mem | awk '{ print 4 }')
mem=2∗mem/100if[[mem -gt heapsize]]thenheapsize=mem
fi
fi
echo $heapsize
return 0
}
#builds the command line and starts the specified java executable
runjava () {
if [[ -n var]]thenevalvar
fi
declare -i niceness
if [[ -n priority]]thenif[[priority = idle ]]
then
niceness=19
fi
#only root can create high priority processes
if [[ priority = high && EUID -eq 0 ]]
then
niceness=-20
fi
fi
declare cl
if [[ -n niceness]]thencl="nice−nniceness 1"elsecl=1
fi
declare fv1=0
if [[ -n initialheapsize]]thenfv1=initialheapsize
fi
declare -i ih=(getheapmemfv1 initialheappercent)if[[ih -gt 0 ]]
then
cl="cl−Xms"ih"m"
fi
declare fv2=0
if [[ -n maxheapsize]]thenfv2=maxheapsize
fi
declare -i mh=(getheapmemfv2 maxheappercent)if[[mh -gt 0 ]]
then
cl="cl−Xmx"mh"m"
fi
if [[ -n opt]]thencl="cl (evalecho"opt")"
fi
declare l4jini={EXECPATH/%.*/.l4j.ini}
if [[ -e l4jini ]]
then
declare inilines=(cat"l4jini")
for il in inilinesdocl="cl (evalecho"il")"
done
fi
declare wholejar
if [[ -n jar]]thenif[[{jar#/} = jar]]thenwholejar=(readlink -f "EXECDIR/jar")
else
wholejar="jar"fifiif[[−nmainclass ]]
then
declare classpath
if [[ -n cp]]thenclasspath=(expandcp "cp")fiif[[−nwholejar ]]
then
if [[ -n classpath]]thenclasspath="wholejar:classpath"elseclasspath="wholejar"
fi
fi
if [[ -n classpath]]thencl="cl -cp "classpath"¨ficl="cl mainclass"elseif[[−nwholejar ]]
then
cl="cl -jar \"wholejar""
fi
fi
if [[ -n cmdline]]thencl="cl (evalecho"cmdline")"
fi
shift
eval cl"@"
return $?
}
#determines the type of dialog to display
declare popuptype
declare realtty
declare xtermcommand
getpopuptype () {
if [[ realtty−eq0]]thenechoconsolereturn0fiif[[x"KDE_FULL_SESSION" = x"true" ]]
then
which kdialog &>/dev/null
if [[ ? -eq 0 ]]
then
echo kdialog
return 0
fi
fi
#x"GNOME_DESKTOP_SESSION_ID" != x"" &&
which zenity &>/dev/null
if [[ ? -eq 0 ]]
then
echo zenity
return 0
fi
which xmessage &>/dev/null
if [[ ? -eq 0 ]]
then
echo xmessage
return 0
fi
#no other method exists for displaying a message so open a new console and print some messages
#if [[ x"$(which x-terminal-emulator)" != x"" ]]
#then
# echo newconsole
# return 0
#fi
#absolutely no way to display a message to the user so dump some data in an error log
#echo dump
return 0
}
showerror () {
declare et
if [[ -n errtitle]]thenet="errtitle"
else
et="0−Error"fiif[[−zpopuptype ]]
then
popuptype=(getpopuptype)fideclaremessage={!1}
which xdg-open &>/dev/null
declare canopen=?declareurlif[[−n2 ]]
then
url=!2if[[canopen−eq0]]thenif[[x"url" = x"downloadurl"]]thenmessage="message\nWould you like to visit the java download page?"
fi
if [[ x"url"=x"supporturl" ]]
then
message="messagenWouldyouliketovisimessage\nPlease visit urlforhelp."fifideclare−irpopuptype" in
"console")
declare mmessage=message//"n"/""echo"et : mmessage"if[[−nurl && canopen -eq 0 ]]
then
select choice in "yes" "no"
do
if [[ x"choice"=x"yes"]]thenurl && canopen -eq 0 ]]
then
dialogtype=--yesno
else
dialogtype=--error
fi
kdialog --title "et"dialogtype "message"result=?
;;
"zenity")
if [[ -n url && canopen -eq 0 ]]
then
dialogtype=--question
else
dialogtype=--error
fi
zenity dialogtype --title "et"−−text"message"
result=?;;"xmessage")if[[−nurl && canopen -eq 0 ]]
then
dialogtype="Yes:100,No:101 -default Yes"
else
dialogtype="Ok"
fi
declare mmessage=message//"n"/""xmessage−buttonsdialogtype -center "mmessage"result=?-100
;;
esac
if [[ canopen -eq 0 && -n url && result−eq0]]thenxdg−openurl
fi
}
#returns 0 if updatedb was run succcessfully or 1 if not
runupdatedb () {
if [[ x"nolocateerror" = x"true" ]]
then
return 1
fi
which updatedb &>/dev/null
if [[ ? -gt 0 ]]
then
return 1
fi
if [[ EUID -ne 0 && realtty -ne 0 && -z xtermcommand ]]
then
return 1
fi
if [[ -z popuptype ]]
then
popuptype=(getpopuptype)fideclareetif[[−nerrtitle ]]
then
et="errtitle"elseet="0 - Invalid locate database"
fi
declare badlocatedb="The locate database is either non-existent or out of date."
declare needrootpw="Please enter the root password to run updatedb (may take a few minutes to complete)."
declare message
if [[ EUID−eq0]]thenmessage="badlocatedb\nWould you like to update it now (may take a few minutes to complete)?"
else
if [[ x"popuptype"=x"console"]]thenmessage="badlocatedb needrootpw"elsemessage="badlocatedb\nWould you like to update it now (requires root password and may take a few minutes to complete)?"
fi
fi
declare message2=message//"n"/""declare−iresultdpopuptype" in
"console")
echo "et:message2"
if [[ EUID−eq0]]thenselectchoicein"yeschoice" = x"yes" ]]
then
result=0
else
result=1
fi
done
else
su root -c updatedb
return ?fi;;"kdialog")kdialog−−title"et" --yesno "message"result=?
;;
"zenity")
zenity --question --title "et"−−text"message"
result=?;;"xmessage")xmessage−buttmessage2"
result=?−100;;esacif[[result -eq 0 ]]
then
if [[ EUID−eq0]]thenupdatedbreturn?
else
#need to open x-terminal-emulator because su will not run unless connected to tty or pty
#but x-terminal-emulator always returns zero so by creating a temp file it will be deleted if su is successful
declare tmpcode=(mktemp)xtermcommand -T "et" -e sh -c "echo \"needrootpw" && su root -c updatedb && rm -f "tmpcode"¨2>/dev/nullif[[−etmpcode ]]
then
rm -f "$tmpcode"
return 1
else
return 0
fi
fi
fi
return 1
}
#extract version number from java -version command
getjavaversion () {
declare jver=("1" -version 2>&1)
if [[ ?−gt0]]thenreturn1fijver={jver#*"}
jver={jver%%\"*}
echo "jver"
return 0
}
#compare against max and min versions
compareminmax () {
if [[ -z 1]]thenreturn1fiif[[−nminversion ]]
then
compare 1minversion
if [[ ?−eq2]]thenreturn1fifiif[[−nmaxversion ]]
then
compare maxversion1
if [[ $? -eq 2 ]]
then
return 1
fi
fi
return 0
}
#try to run using a default java
trydefault () {
compareminmax (getjavaversion"1")
if [[ ?−eq0]]thenrunjava"@"
exit ?
else
#still try to run using java's version:release option, if it fails then continue with a search, a problem here is that there is no way to distinguish if the error occurs within java or the application, interpret an error within two seconds of launching as being a java error
if [[ -n maxversion ]]
then
return 0
fi
declare oldopt="opt"if[[−n"opt" ]]
then
opt="opt−version:minversion+"
else
opt="-version:minversion+"fideclare−ielapsed=SECONDS
runjava "@"declareresult=?
elapsed=SECONDS−elapsedif[[result -eq 0 || elapsed -gt 2 ]]
then
exit resultelseopt="oldopt"
fi
fi
return 0
}
#find highest java version
findbest () {
declare jv
declare jp
for jpath in @doif[[!−ejpath || ! -r jpath]]thencontinuefiif[[−njdkpreference ]]
then
if [[ "jdkpreference"="jreonly" ]]
then
jtype jpathif[[? -eq 1 ]]
then
continue
fi
fi
if [[ "jdkpreference"="jdkonly" ]]
then
jtype jpathif[[? -ne 1 ]]
then
continue
fi
fi
fi
declare jver=(getjavaversionjpath)
compareminmax jverif[[? -gt 0 ]]
then
continue
fi
if [[ -n jv && -n jp ]]
then
compare jverjv jpathjp
if [[ ?−eq1]]thenjv="jver"
jp="jpath"fielsejv="jver"
jp="jpath"fidoneecho"jp"
}
#script execution starts here
#check if we are connected to a real terminal, if not and headertype=console spawn one
tty -s
realtty=?if[[realtty -ne 0 ]]
then
which x-terminal-emulator &>/dev/null
if [[ ? -eq 0 ]]
then
xtermcommand="x-terminal-emulator"
else
which xterm &>/dev/null
if [[ ? -eq 0 ]]
then
xtermcommand="xterm"
fi
fi
if [[ x"headertype"=x"console" ]]
then
if [[ -n xtermcommand]]thenxtermcommand -e "0""@"
else
showerror "This application needs to be run from a terminal."
fi
exit ?
fi
fi
#you can override the launcher settings by providing command line options, launcher options are prefixed with --jnixopt eg. --jnixoptminversion=1.5.0, options with spaces must be escape quoted eg. --jnixoptpath=\"/usr/sun java/bin/java\"
declare -a newargs
declare -i position=1
while [[ -n "1" ]]
do
declare o="1"declarejno={o#--jnixopt}
if [[ x"jno"!=x"o" ]]
then
eval "jno"elsenewargs[position]="o\"
position=position+1
fi
shift
done
#export these for use in java invocation
declare export EXECPATH="0"declareexportEXECDIR=(readlink -f (dirname"0"))
if [[ -n chdir]]thendeclaremcd={chdir#/}
if [[ x"mcd"=x"chdir" ]]
then
cd "EXECDIR/chdir"
else
cd chdir
fi
fi
#first try to run using internal java path
if [[ -n path ]]
then
if [[ -e path]]thenrunjavapath "newargs[@]"exit?
else
if [[ -z minversion && -n jar ]]
then
showerror bundledjreerr supporturl
exit 1
fi
fi
fi
#if version information is supplied check some defaults
if [[ -n minversion∣∣−nmaxversion ]]
then
#try JAVAHOMEif[[−nJAVA_HOME ]]
then
trydefault "JAVAHOME""{newargs[@]}"
fi
code
#then java in path
which java &>/dev/null
if [[ $? -eq 0 ]]
then
trydefault java "${newargs[@]}"
fi
fi
#if pathisnotnulldoasearchofpath parents to find alternate java installations
if [[ -n path]]thendeclarepathroot=path
while [[ ! -e "pathroot"]]dopathroot=(dirname "pathroot")donedeclareprj=(find "pathroot"−namejava−typef(findbest prj)if[[−n"pj" ]]
then
runjava "pj""{newargs[@]}"
exit ?
fi
fi
#prefer to use locate since its fast
declare javapaths=(locate -i -w -A "/bin/java" 2>/dev/null)
#if locate fails fallback to using find
if [[ ?−gt0∣∣x"javapaths" = x"" ]]
then
#prompt user to run updatedb
runupdatedb
if [[ ?−eq0]]thenjavap(locate -i -w -A "/bin/java" 2>/dev/null)
else
javapaths=(find/−namejava−typef−(findbest javapaths)if[[−n"jp" ]]
then
runjava "jp""{newargs[@]}"
exit $?
else
showerror jreversionerr downloadurl
exit 1
fi
#do not remove the blank line below
Certainly! I'd be happy to help explain the Bash script you've provided. This script is designed to be a robust launcher for Java applications on Unix-like systems. It handles various tasks such as finding the appropriate Java Runtime Environment (JRE), checking Java versions, setting environment variables, and managing errors.
Below, I'll break down the script into its main components and explain how each part works.
Shebang (#!/bin/bash): Specifies that the script should be run using the Bash shell.
Variables:
headertype: Determines the type of user interface (e.g., gui or console).
jar: The path to the Java archive file. By default, it uses the script itself ("$0"), allowing the script to be a wrapper for a JAR file.
errtitle: The title used for error messages.
downloadurl: URL to download Java if it's not installed.
supporturl: URL for support.
priority: Sets the process priority (normal, high, or idle).
minversion: The minimum required Java version.
jdkpreference: Preference for using JRE or JDK (preferJre, preferJdk, jreOnly, jdkOnly).
2. Function Definitions
a. jtype(): Determine Java Type
bash
jtype () {
# Determines if a Java path points to a JRE or JDK.
# Returns 0 for JRE, 1 for JDK, 2 if unspecified.
# Behavior depends on `jdkpreference`.
}
Purpose: Checks if a given Java executable path is a JRE or a JDK based on the jdkpreference.
Usage: Helps decide which Java installation to use when multiple are available.
b. checkextra(): Process Version String
bash
checkextra () {
# Processes the Java version string to handle suffixed versions (e.g., "-ea").
# Returns modified version string and a flag indicating if there was extra information.
}
Purpose: Cleans up the Java version string for accurate comparison.
Usage: Ensures version comparisons are not affected by extra labels like -ea (Early Access).
c. extractvn() and extractrvn(): Extract Version Numbers
bash
extractvn () {
# Extracts the primary version number segment.
}
extractrvn () {
# Extracts the remaining version number segments.
}
Purpose: Breaks down version numbers into segments for detailed comparison.
Usage: Used by the compare() function to compare Java versions segment by segment.
d. compare(): Compare Java Versions
bash
compare () {
# Compares two Java version strings.
# Returns 0 if equal, 1 if first is higher, 2 if second is higher.
}
Purpose: Determines which of two Java versions is newer.
Usage: Helps in selecting the most suitable Java installation.
e. getheapmem(): Calculate Heap Memory
bash
getheapmem () {
# Calculates heap memory size based on fixed and percentage values.
}
Purpose: Determines the appropriate heap size for the Java application.
Usage: Ensures the Java application starts with optimal memory settings.
Purpose: Builds the full classpath by resolving any patterns and making paths absolute.
Usage: Prepares the classpath for the Java command.
g. runjava(): Execute Java Application
bash
runjava () {
# Constructs and executes the Java command with the appropriate options.
}
Purpose: Central function to run the Java application with all configurations.
Key Steps:
Sets environment variables if defined.
Adjusts process priority if necessary.
Calculates initial and maximum heap sizes.
Builds the command line with all Java options, classpath, and main class or JAR.
Handles any additional command-line arguments.
Executes the Java command.
h. getpopuptype(): Determine Dialog Method
bash
getpopuptype () {
# Determines the method to display messages based on the environment.
# Options include console output, kdialog, zenity, xmessage, or spawning a new console.
}
Purpose: Detects the user's environment to choose the best way to display messages or errors.
Usage: Ensures error messages are visible to the user, whether they are using a GUI or a console.
i. showerror(): Display Error Messages
bash
showerror () {
# Displays an error message using the method determined by `getpopuptype()`.
# Optionally offers to open a URL (e.g., download page).
}
Purpose: Provides user-friendly error messages and guidance.
Usage: Informs the user about issues like missing Java installation and offers solutions.
j. runupdatedb(): Update locate Database
bash
runupdatedb () {
# Attempts to run `updatedb` to refresh the file index used by `locate`.
}
Purpose: Ensures the locate database is up-to-date for accurate Java executable search.
Usage: Helps the script find Java installations more efficiently.
k. getjavaversion(): Retrieve Java Version
bash
getjavaversion () {
# Extracts the Java version string from the output of `java -version`.
}
Purpose: Retrieves the version of a Java executable.
Usage: Used to check if the Java installation meets version requirements.
l. compareminmax(): Check Version Range
bash
compareminmax () {
# Checks if a Java version is within the specified min and max versions.
}
Purpose: Validates that a Java version meets the script's requirements.
Usage: Ensures the selected Java executable is compatible.
m. trydefault(): Attempt to Use Default Java
bash
trydefault () {
# Tries to run the Java application using a given Java executable.
# Checks if the version is acceptable.
}
Purpose: Attempts to use the default Java installation before searching for others.
Usage: Prioritizes using standard Java paths like JAVA_HOME or java in the system path.
n. findbest(): Find Best Java Installation
bash
findbest () {
# Searches through a list of Java paths to find the best one based on version and preferences.
}
Purpose: Identifies the most suitable Java executable when multiple are available.
Usage: Helps select the optimal Java installation according to the script's requirements.
3. Main Script Execution
a. Terminal Check and Handling
bash
# Checks if the script is connected to a terminal.
tty -s
realtty=$?
# If not connected and `headertype` is set to console, attempts to launch a terminal emulator.
Purpose: Ensures the script can interact with the user if needed.
Behavior:
If not running in a terminal and headertype is console, tries to open a terminal emulator and re-runs the script.
If no terminal emulator is available, shows an error.
b. Command-Line Arguments Processing
bash
# Processes arguments to allow overriding of script options.
# Looks for arguments prefixed with `--jnixopt` and evaluates them.
Purpose: Allows users to override default settings via command-line options.
Usage: For example, --jnixoptminversion=1.8.0 to set a different minimum Java version.
c. Environment Setup
bash
# Sets `EXECPATH`, `EXECDIR`, and optionally changes the working directory.
Purpose: Prepares environment variables for use in the script and Java application.
d. Java Execution Attempt
Using Specified Java Path:
bash
if [[ -n $path ]]; then
if [[ -e $path ]]; then
runjava $path "${newargs[@]}"
exit $?
else
# If JRE is missing and no minimum version is specified, shows error and exits.
if [[ -z $minversion && -n $jar ]]; then
showerror bundledjreerr supporturl
exit 1
fi
fi
fi
Purpose: Tries to use a Java executable specified in $path.
Behavior: If the path doesn't exist, handles the error appropriately.
Using Default Java Installations:
bash
if [[ -n $minversion || -n $maxversion ]]; then
# Tries $JAVA_HOME
if [[ -n $JAVA_HOME ]]; then
trydefault "$JAVA_HOME" "${newargs[@]}"
fi
# Tries `java` in system path
which java &>/dev/null
if [[ $? -eq 0 ]]; then
trydefault java "${newargs[@]}"
fi
fi
Purpose: Attempts to use the Java installation pointed to by JAVA_HOME or available in the system path.
Behavior: Checks if the Java version meets requirements before running.
Searching for Java Installations:
bash
# Searches using `locate` or `find` to find Java executables.
# Uses `findbest()` to select the most suitable one.
Purpose: Searches the system for available Java installations.
Behavior: If no suitable Java is found, shows an error message prompting the user to install Java.
4. Error Handling and User Interaction
Error Messages:
Missing Java Installation:
bash
showerror jreversionerr downloadurl
exit 1
Prompts the user to install Java if it's not found.
Bundled JRE Missing:
bash
showerror bundledjreerr supporturl
exit 1
Alerts the user if the script expects a bundled JRE that is missing or corrupted.
User Prompts:
Uses zenity, kdialog, or xmessage to display GUI dialogs if available.
Falls back to console prompts if no GUI method is available.
Offers to open a URL (e.g., Java download page) if appropriate.
5. Script Usage Notes
Customizing Options:
Users can override default options by passing command-line arguments prefixed with --jnixopt.