Bashj programming guide

De Lillois Fractale Wiki
Aller à la navigation Aller à la recherche

This is a complement to the general bashj introduction page.

Here is the bashj install link.

Understanding the architecture of bashj

The key idea behind bashj is the execution of a bashj server. It is a JVM instance performing essentially two tasks

  1. translate bashj code into bash code
  2. execute any java method call for any running bashj client

The benefit of this is the extreme efficiency of this minimal architecture, taking advantage of combined strengths of java & bash.

The following slide explains the global flows of bashj

Bashj overview.png

But the developper of a bashj script should be aware of the fact that any global component of the JVM (static variables, Threads,...) will be shared with all other bashj clients launched.

For instance if a client modifies a static variable during the execution of a bashj script, the next execution of the same script will start with the modified value of that variable. This may be convenient ... or a benefit, depending on situations.

Similarly, if a bashj client launches a Thread without closing it, this Thread will survive in the server JVM (which may not be the intention).

Composition of a bashj script file

A bashj script contains typically 3 components

  1. the header
  2. the java section
  3. the bash / bashj section


The file shebang header is a mandatory line


Java section

The java section is optional. Without this part, the script behaves exactly as a bash script file with the same content.

The java section starts with a line


and it ends with one of the lines


The java section is similar to a java class source. However, the package line, the class line and the class global braces are omitted.

It is possible (and often necessary) to include import lines.

Only public static will be accessible from the bashj section. A line starting with static is considered as public.

The implicit className is "j". So a function public static int factorial(int n) will be called in the script bash section as j.factorial(int).

Calling getClass().getName() is allowed but will provide unusable and irrelevant results.

Bash / bashj section

This section is also optional.

If absent, the execution becomes a pure java 'interpreter' (see below).

If present, it includes standard bash lines, with the possible presence of java calls.

The java call translation is enabled with the directive


and disabled with the directive


The java calls are detected by the source processor thread when the translation is enabled. They are coded in either form:


For instance


The result of such calls may be used to produce bash shell values, and for instance:

echo Math.hypot(4.0,3.0) 
ZZ = Math.hypot($XX,$YY) 

It is recommended not to use complex bash expressions as arguments to java method calls.

It is recommended and often necessary to use double quotes vars as arguments to java calls (to handle spaces, comma, parenthesis and other special shell characters).

WORD="Hello, world ()#\$!"
echo "index of [$LETTER] in [$WORD] is" u.indexOf("$WORD","$LETTER")

Java static fields are detected like java methods. For instance


Knowing how the detection / substitution works, it is the developer responsibility to avoid in the bash section unintended detectable expressions. The source processor is unable to handle and avoid all complex bash constructions. For instance this bash line

tr Math.PI z < $FILE  # Noooo !

is strange but valid with bash, but it is likely to raise unwanted results with bashj...

Java calls in bashj section

Several families of java methods & fields may be called

  • Those defined in the beginning of the running bashj script itself in the java section. Java methods are defined there without package name and without class name. The implicit class name is "j". So a function public static int factorial(int n) may be called in the script bash body as j.factorial(int)
  • Those present in the standard java classes (java.lang.System , java.lang.Math  etc ...). The list of  standard classes is defined in /opt/bashj/import file. It is extensible and configurable.
  • The control methods provided by the bashj server:                       # simple info provided by the running bashj server
u.status()                     # detailed info provided by the running bashj server
u.classes()                    # classes accessible using bashj
u.classes(String grep)         # filtered classes accessible using bashj
u.methods()                    # methods accessible using bashj
u.methods(String grep)         # filtered methods accessible using bashj
u.fields()                     # fields accessible using bashj
u.fields(String grep)          # filtered fields accessible using bashj
u.scriptName()                 # name of current script
u.serverPid()                  # server process id
u.accessibleClass(String className)    # Checks access to a given class
u.uDoc()                       # documentation on the global list of u methods
  • Those provided as utilities as part of bashj. They are also accessible with a class name "u", for instance u.toUpperCase(String) or yellow(String). The list is available using bashj +uDoc. It frequently grows.
  • Those present in jars put by the user in the subdirectory jarlib. This allows users to easily extend bashj capabilities, and to possibly create bash/bashj modules.

Coding rules

String arguments : String arguments should always be double quoted in the bashj section. The correct way to use String arguments is:

A="Hello, world"

Boolean returned values. Bash and java have very different concepts related to booleans. To test return values of boolean java calls, use this:

if [ $CONFIRM == true ]  ... else ...

Special characters. It is not allowed to use some greek characters φ χ ψ τ h in bashj sources (they are detected and used by the preprocessor).

Embedded calls. It is not possible to embed bashj java method calls (  Math.log(Math.sin($X)) will not work).

From bash to bashj

A bashj file is similar to a standard bash file. Just replace the shebang : #!/usr/bin/bashj instead of #!/bin/bash. A bash script will be processed by bashj exactly like it is processed by bash.

The bashj interpreter only works for scripts. It may not be used for an interactive session.

However It is also possible to use interactively calls to the bashj interpreter:

bashj "u.doubleEval(x*cos(x),0.25)"

and to put in bash scripts:

FX=`bashj "u.doubleEval(x*cos(x),0.25)"`

Modularity and extensibility

Java classes and packages are easy to add to bashj. The steps are simple:

  • create anywhere one or many java classes with some static public methods and/or fields.
  • compile them and put the class file(s) in a jar file
  • place this jar in the directory /opt/bashj/jarlib
  • restart the bashj server using bashj -restart 
  • Any script has now the capacity to call the new methods and fields in both the java section and the bashj section. 

Concurrency issues

Concurrent execution of multiple bashj scripts will raise problems if some of the called methods are blocking. This happens for sleeping Threads, for UI blocking dialogs, and possibly for any method waiting for delayed results. The server processes all calls sequentially [ improvement expected ? ].

2 simple workarounds for this

  • organize and use only methods providing rapid answers; or
  • avoid concurrent executions of bashj scripts

Using bashj as a pure java 'interpreter'

It is possible to create a bashj page without any bash line. In this case, the interpreter will automatically call and execute the method  static void main(String... a) , as in this example:

static void main(String... a)
{u.p("Hello world, welcome to bashj");}

This minimal but complete code will execute as expected. "Interpreter" is not what people would probably expect: the code is actually executed through the server JVM.

Convenience u methods

Various convenience methods are include with bashj. It is recommended to cheks their list using the command

bashj +uDoc

or their javadoc.

Swinging bash (bash with swing user interface)

As any other java package, it is possible to take advantage of Swing UI components, and this provides (through bashj) a windowing interface to bash.

Here is a minimal example:

import javax.swing.JFrame;
import javax.swing.JOptionPane;
static void main(String... a)
{JOptionPane.showMessageDialog​(new JFrame(),"Welcome to bashj swing UI");}

The same swing tasks may be achieved using convenient u methods:

TITLE="bashj msg"
MSG="Welcome to bashj swing UI"
ERMSG="There is a problem!"
QUESTION="Do you confirm ?"

Inter process communication using bashj

Given the persistence features of the bashj server, it is easy to set up fast IPC between bashj scripts.

The following u methods allow to set() and get() inter process variables:

public static void set(String key,String value,boolean scriptSpecific,boolean persist)
public static String get(String key,boolean scriptSpecific,boolean persist)
public static void set(String key,String value)
public static String get(String key)

The scriptSpecific flag indicates whether this value is shared or not with other scripts. These values will be kept during successive calls of the calling scripts, until the server is stopped.

The persist flag indicates whether the values should persist in the host  file system. These values will be saved when the server is stopped.

The simple calls (without boolean parameters) assume scriptSpecific is true, persist is false.

Script coding examples

Here are some basic examples, extracted from the wider list of examples provided as part of the installation process (example subdir).

static int factorial(int n) 
{if (n<=0) return(0);
 if (n==1) return(1);
echo j.factorial(10)


static void main()
{u.p("Hello, bashj  world !");
 u.p("This code is executed in a JVM "+System.getProperty("java.version"));
 u.p("But it is processed through bashj and finally bash");}


echo Math.cos(0.5)
echo Math.hypot(3.0,4.0)
echo System.getProperty("java.runtime.version")


static String ax2_bx_c(double a,double b,double c)
{final double r=b*b-4*a*c;
 if (r<0.0) return("NoRoot");
 if (r==0.0) return(""+(-b/(a+a)));
 final double sq=Math.sqrt(r);
 return(""+(-b-sq)/(a+a)+" "+(-b+sq)/(a+a));}
echo "... Delivers the roots of a quadratic equation"
echo "... Solving $A X^2 + $B X + $C"
echo "... Roots are " j.ax2_bx_c($A,$B,$C)


echo "bashj server utilities"


echo "bashj string utilities"
echo length of $WORD is u.strlen($WORD)
echo index of $LETTER in $WORD is u.indexOf($WORD,$LETTER)
echo Uppercase u.toUpperCase($WORD)
echo Lowercase u.toLowerCase($WORD)