One of the main maintenance issues with running a Java application from a shell script is keeping your classpath up-to-date with the new and updated jars. To make things more difficult you can’t specify a folder as the classpath as it doesn’t include the jars in it only .class files. However through the use of a basic for loop we are able to dynamically generate the classpath.
CP=
for i in `ls ./lib/*.jar`
do
CP=${CP}:${i}
done
-cp, bash, Classpath, Java, Shell Script, Tips & Tricks, Unix
Often when working with Bash scripts we find that we want to add some options to the script by way of arguments or variables. Easily enough Bash command line arguments can be accessed by $1, $2, etc within the script where $1 is the first argument or variable and #2 is the second etc.
Example:
#!/usr/bin/env bash
echo the first argument is $1
echo second argument is $2
echo eleventh argument is $11
echo total number of arguments is $#
Resources:
Arguments, bash, Command Line, parameters
As one that seldom finds himself having to run Java Applications from a Unix Bash Script, I thought it would be helpful to share the appropriate commands i use to execute the code and to notify the user of success or failure. For reference the folder structure I use is:
where the lib folder contains all necessary jar files to run the application, and the config folder contains any properties or configuration files passed as run time arguments
Writing the script
- Specify the script is a bash script
- Define SUCCESS and FAILURE variables
- Define the appdirectory
- Define the lib folder variable
- Define the classpath variable. This is a : seperated list of jars needed by the application
CP=${LIB}abc.jar:${LIB}xyz.jar
- Define java home
APP_JAVA_HOME=/usr/jdk/instances/jdk1.5.0
- Execute the Application with any arguments and java settings
${APP_JAVA_HOME}/bin/java -ms256m -cp "${CP}"
com.mdibtz.TestApp "${APP_HOME}/config/config.properties"
- Test for Failure
if [ $? -ne 0 ]
then
exit ${FAILURE}
fi
- Success Logic if needed
Complete Script
#!/bin/bash
FAILURE=1
SUCCESS=0
APP_HOME=`pwd`
LIB=${APP_HOME}/lib/
CP=${LIB}activation-1.1.jar:${LIB}mail-1.4.jar
APP_JAVA_HOME=/usr/jdk/instances/jdk1.5.0
${APP_JAVA_HOME}/bin/java -ms256m -mx768m -cp "${CP}"
com.mdbitz.TestApp "${APP_HOME}/config/config.properties"
if [ $? -ne 0 ]
then
echo "AppFailed during run"
exit ${FAILURE}
fi
echo "App successfully run"
exit ${SUCCESS}
bash, java application, run java on unix, Unix