Bash Script Naming – Say My Name, Say My Name!

|

I use Java as my main Linux server programming language these days and so I usually have a Bash script to go along with each program. The Bash script help encapsulate creating the proper CLASSPATH needed to run the Java program, calls the correct Java class and also passes through any command line parameters that I might need. Recently I had several Java programs that I wrote and bundled inside the same jar file which I needed to call separately. They had all of the same CLASSPATH and environment requirements, so why should I create separate Bash scripts for each one?

What’s In A Name?

Instead of a separate Bash script for each Java program I used a neat little feature of Linux called symbolic linking. I create in a “bin” subdirectory my main Bash script and then link to it using distinct names from the main program directory. The script then detects what names is being used to call it and executes the appropriate Java class. Some of the Bash code looks like this:

#!/bin/bash
# Filename: JavaCaller

# Get the name of the script (or the name it was called as)
RSCRIPT="`basename $0`"

# Do not allow the script to be called directly
if [ "${RSCRIPT}" = "JavaCaller" ]; then
  echo "Please do not call script directly."
  exit 1

# Run the Java class that matches the script name
else
  RUN_CLASS="com.franzone.${RSCRIPT}"
fi

# Run the java program
java ${RUN_CLASS} $@

Notice the $@ command line parameter in the call to the Java class? That simply passes on the command line parameters used to call the script to the Java program.

So you can see, if I had a Java program in the com.franzone package who’s class name was TestOne, then I could create a symbolic link to my JavaCaller script to call it like this:

ln -s bin/JavaCaller TestOne

Now from the main directory I could call the ./TestOne script (symbolic link) which would actually execute the JavaCaller script with the TestOne name. That would cause my Bash script to call the TestOne Java class. Cool, eh?