How to execute a java script with jshell?

It turns out that with a bit of trickery there is a way, although I haven't fully managed to suppress the interpreted commands but pretty close to what I want.

Change test.jsh to:

#!/usr/bin/env sh
tail -n +4 "$0" | jshell -s "$@"
exit $?
System.out.println("Hello World")
/exit

Which gives us:

⚡ ./test.jsh
-> System.out.println("Hello World")
Hello World
-> /exit

Use

//usr/bin/env jshell --show-version --execution local "$0" "$@"; exit $?

as the first line of test.jsh. The test.jsh script could look like:

//usr/bin/env jshell --show-version "$0" "$@"; exit $?
System.out.println("Hello World")
/exit

The command line option --show-version is optional, of course, but gives immediate feedback that the tool is running.

The extra command line option --execution local prevents jshell to spawn another VM. This speeds up launch time and if an exception is thrown by your script code, the local VM will exit.

Consult the output of jshell --help and jshell --help-extra for more options.

Update

Also take a look at https://github.com/jbangdev/jbang Having fun with Java scripting, which offers a neat wrapper around running .java files from the command line.