How to pass arguments to a jshell script?

And what about option -R

> jshell -v -R-Da=b ./file.jsh

for script

{
  String value = System.getProperty("a");
  System.out.println("a="+value);
}
/exit

will give you

> jshell -v -R-Da=b ./file.jsh
a=b

Another way, would be following:

{
  class A {
    public void main(String args[])
    {
        for(String arg : args) {
          System.out.println(arg);
        }
    }
  }

  new A().main(System.getProperty("args").split(" "));
}

and execution

> jshell -R-Dargs="aaa bbb ccc" ./file_2.jsh

Update

Previous solution will fail with more complex args. E.g. 'This is my arg'.

But we can benefit from ant and it's CommandLine class

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")));
}

and then, we can call it like this:

jshell --class-path ./ant.jar -R-Dargs="aaa 'Some args with spaces' bbb ccc" ./file_2.jsh
aaa
Some args with spaces
bbb
ccc

Of course, ant.jar must be in the path that is passed via --class-path


Oracle really screwed this up, there is no good way to do this. In addition to @mko's answer and if you use Linux(probably will work on Mac too) you can use process substitution.

jshell <(echo 'String arg="some text"') myscript.jsh

And then you can just use arg in myscript.jsh for example:

System.out.println(arg) // will print "some text"

You can simplify it with some bash function and probably write a batch file that will write to a temp file and do the same on windows.

Tags:

Java 9

Jshell