How to run a JShell File?

JShell is not meant to run a Java class directly. If you want to run a java class, you still need to do it the old way - java <your-class-name>.

From the docs,

The Java Shell tool (JShell) is an interactive tool for learning the Java programming language and prototyping Java code. JShell is a Read-Evaluate-Print Loop (REPL), which evaluates declarations, statements, and expressions as they are entered and immediately shows the results.

As per this quote, JShell is meant for running or trying out individual Java statements. In the traditional java way, you have to write a full Java program before you can run it and see the results. But JShell allows you a way to try out the Java statements without needing you to build the full standalone java application.

So the short answer to your question is that, no, you can't call standalone java applications like jshell my-jshell-skript.java. However, you CAN call a script file which contains individual JShell commands or Java statements. So if you copy all the statements from your Java program and paste them to a JShell script, you can run the script like:

% jshell my-jshell-skript.jsh

But this is not quite the same as running a standalone java application.


You can pipe the string to JShell:

echo 1 + 2 | jshell

Example:

:/# echo 1 + 2 | jshell
|  Welcome to JShell -- Version 9
|  For an introduction type: /help intro

jshell> 1 + 2
$1 ==> 3

:/#

Or, from a file:

cat myfile | jshell

Where myfile contains the line "1 + 2".


You can create a Jshell script file named some.jsh with those statements and on the command prompt from where you run jshell, execute it as:-

jshell /path/to/some.jsh

On a MacOSX, I would do something like:

enter image description here