One issue that I always come across when creating a shell script is referencing files dynamically based on the location of the shell script. A hack I often used was to pass the script’s path to the script on execution because the readlink command was not available to me. However recently I have revisited this issue and have found a solution for obtaining the absolute path of the executing shell script without readlink. For your convenience both scripts are found below.
Absolute Path using readlink
#!/bin/sh
PATH= $(dirname $(readlink -f $0))
echo ${PATH}
Absolute Path without using readlink
#!/bin/sh
ORIGINAL_PATH=`pwd`
cd "`dirname ${0}`"
PATH=`pwd`
cd "${ORIGINAL_PATH}"
echo ${PATH}
absolute path, pwd, readlink, Shell Script, Tips & Tricks, Unix
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
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