How to run a Java Application from Bash Script

http://resources.mdbitz.com/2009/11/how-to-run-a-java-application-from-bash-script/

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

#### CMD LINE ?????? ==========================

nohup java.jar.sh &

#### CMD LINE ?????? ==========================

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}