javashebang

First of all: what is shenbag ?
From Wikipedia Shebang_(Unix):
In computing, a shebang (also called a sha-bang, hashbang, pound-bang, or hash-pling), is the character sequence consisting of the characters number sign and exclamation mark (that is, “#!“) at the beginning of a script. Some examples are the following:
#!/bin/bash
#!/bin/ksh
#!/bin/sh
#!/usr/bin/env php
#!/usr/bin/expect -f
#!/usr/bin/ksh
#!/usr/local/bin/expect

For using Java language on scripting (Linux, UNIX, etc.) you have to:

  • Write the java code using an IDE (Eclipse, for example)
  • Compile the class
  • Create a jar package (not mandatory but it is better to create)
  • Create a shell script *.sh for running the Java class
  • Distribute all with a zip or tar.gz file

My idea is “How can I simplify this ?”. My requirements are the following:

  • Write the java code directly in a file-script
  • Compile it if the script changed
  • Compile it if the java version changed
  • Run it
  • Read parameters from the command line
  • Add external libraries

This is an example of my javashebang:

#!/bin/javashebang
#START_JSH
#JAVA_HOME=${JAVA_HOME}
#JAVA_OPTS=-Xms256m -Xmx1024m
#END_JSH

public class HelloWorld {

public static void main(String[] args) {
if (args.length == 0) {
System.err.println(“Parameters: VALUES”);
System.exit(1);
}
System.out.println(“There are ” + args.length + ” parameters:”);
for (int j=0; j<args.length; j++) {
System.out.println(“args[” + j + “]=” + args[j]);
}
System.exit(0);
}
}

The output is the following:

./HelloWorld.jsh
Parameters: VALUES

The folder contains the following files:

  • HelloWorld.jsh -> the source script
  • HelloWorld.java -> the java class extracted from the script
  • HelloWorld.class -> the java class compiled

Requirements:

  • A UNIX System (Linux, AIX, etc)
  • A JDK installed (not JRE): OpenJDK, Oracle JDK, IBM JDK, etc.

Features:

  • Option “-d” for debugging
  • Option “-v” for verbose output
  • Option “-f” for forcing to compile
  • Extension of the script is “*.jsh” (suggested, not mandatory)
  • The script MUST TO have the same name as the java class (mandatory)
  • The java class MUST TO have the static method main (mandatory)
  • Header of the file “#JAVA_OPT” for managing the options on java command line tool
  • Header of the file “#JAVAC_OPT” for managing the options on javac command line tool
  • Header of the file “#JAVA_HOME” for running java, javac and javap command line tools
  • Header of the file “#JAVA_CLASSAPTH” for managing the options on javac and java command line tools
  • Test on Linux (Ubuntu) and AIX

Setup

  1. Download the code of javashebang from my git repository.
  2. You can download some examples from this git examples.
  3. Copy the file on /bin/javashebang
  4. sudo chmod 755 /bin/javashebang
  5. Use it