jshell and command line arguments

If you start your experience with jshell, you will notice that passing command line arguments to your script may be a struggle. Typically, you would expect something like this

> jsell my_script.jsh arg1 'some other arg' yet_another arg

to be working such way, arguments are passed to your script. This is not the case here. The reason for this is, jshell takes a list of files as arguments and parses them for it’s own.

However, you can overcome this issue. And, you can even make it very flexible thanks to Apache ANT. Make sure to get ANT (e.g. 1.10) and put it somewhere. Also, make sure to set ANT_HOME such way it points to your ANT installation.

Then, you can do following inside script

8< -- CUT HERE --- CUT HERE ---- jshell_script_file ---- CUT HERE -- CUT HERE ---

import org.apache.tools.ant.types.Commandline;
{
  class A {
    public void main(String args[]) {
      for(String arg : args) {
        System.out.println(arg);
      }
    }
  }
  new A().main(Commandline.translateCommandline(System.getProperty("args")));
}
/exit

8< -- CUT HERE --- CUT HERE --- CUT HERE --- CUT HERE --- CUT HERE -- CUT HERE ---

and you can call it like this

# -R will pass arguments for runtime. In this sample we pass -D and it sets system property "args"
# to value 'Some arg with spaces' $SHELL $TERM some_other_arg
#
> jshell --class-path $ANT_HOME/lib/ant.jar \
  -R-Dargs="'Some arg with spaces' $SHELL $TERM some_other_arg" \
  ./jshell_script_file
Some args with spaces
/bin/bash
xterm-256color
some_other_arg