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
, , , , , ,

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:

, , ,

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:

app_name
    - lib
    - config

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

  1. Specify the script is a bash script
    #!/bin/bash
  2. Define SUCCESS and FAILURE variables
    FAILURE=1
    SUCCESS=0
  3. Define the appdirectory
    APP_HOME=/tmp/app
  4. Define the lib folder variable
    LIB=${APP_HOME}/lib/
  5. Define the classpath variable. This is a : seperated list of jars needed by the application
    CP=${LIB}abc.jar:${LIB}xyz.jar
  6. Define java home
    APP_JAVA_HOME=/usr/jdk/instances/jdk1.5.0
  7. 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"
  8. Test for Failure
    if [ $? -ne 0 ]
    then
        exit ${FAILURE}
    fi
  9. Success Logic if needed
    exit ${SUCCESS}

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}
, , ,