Home > bash, coding, cygwin, java, linux, mac os > Start script for stand-alone Java process

Start script for stand-alone Java process

Directory structure

  • lib
    • some.jar
    • another.jar
  • config
    • dev
    • uat
  • start.sh
  • .setenv.sh

.setenv.sh

#!/bin/bash 

# environment (typically 'dev', 'uat' or 'prod') 
env=

# absolute path to java home ( >= 1.7 ) 
# such that $java_home/bin/java exists 
java_home=${JAVA_HOME} 

# add any additional environment setup here:

start.sh

#!/bin/bash 

# script should exit if any command fails 
set -e 

function envfail() { 
  echo $1; 
  echo "Please adjust $setenv_script and retry ..." 
  exit 1 
} 
function check_not_empty() { 
  if [ -z "$1" ]; then 
    envfail "Variable '$2' is unset or empty." 
  fi 
} 

script=$(readlink -f "$0") 
if [[ "$script" =~ .*[[:space:]].* ]]; then 
  echo "Script path contains spaces: $script" 
  echo "Please fix and retry ..." 
  exit 1 
fi 

# ok, now we know $script contains no spaces so 
# we don't need quoting acrobatics from here on 

dir=$(dirname $script) 
parent=$(dirname $dir) 
setenv_script=$parent/setenv.sh 

if [ ! -e $setenv_script ]; then 
  echo "$setenv_script not found" 
  cp $dir/.setenv.sh $setenv_script 
  envfail "Created a default $setenv_script for you." 
fi 
setenv_script_file=$(readlink -f $setenv_script) 
if [ -r $setenv_script_file ]; then 
  echo "Sourcing $setenv_script" 
  source $setenv_script 
else 
  envfail "Cannot read $setenv_script" 
fi 

check_not_empty "$env" 'env' 
config_env=$(readlink -f "$dir/config/$env") 
if [[ ! -r "$config_env" || ! -d "$config_env" ]]; then 
  envfail "Invalid env=$env : Cannot read directory $config_env" 
fi 

check_not_empty "$java_home" 'java_home' 
java="$java_home/bin/java" 
if [ ! -e "$java" ]; then 
  envfail "$java is not an executable file" 
fi 
java_version=$("$java" -version 2>&1 \
               | head -n 1 | cut -d'"' -f2 | cut -d'.' -f2) 
if [ $java_version -lt "7" ]; then 
  envfail "Java 1.7 or higher is required." 
fi 

# turn on bash debug output for the following lines 
set -x 

cd $dir 
mkdir -p "../log" 

nohup \ 
"$java" -cp "$config_env:lib/*" \
        net.doepner.example.Main \ 
        > "../log/example_stdout.log" 2>&1 & 
Advertisements
Categories: bash, coding, cygwin, java, linux, mac os
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: