JShell, which has been introduced since Java 9, is an interactively evaluates declarations, statements, and expressions of the Java programming language in a read-eval-print loop (REPL). This tutorial is going to show how to execute and exit a script with JShell.
To learn more about JShell commands, please visit Java 9 JShell Cheat Sheet.
1. Execute A Script With JShell
To execute a script with JShell, we can use the following syntax:
1 |
jShell <path-to-the-script> |
For example, let’s see a simple script /opt/HelloJShellScript.java with the content as follows:
1 2 3 4 5 6 7 8 9 |
int square(int i1) { return i1 * i1; } for(int i = 0; i< 5; i++){ System.out.println(String.format("Square of %d is %d", i, square(5))); } /exit |
To run the script with JShell:
1 |
jshell /opt/HelloJShellScript.java |
Let’s see the output of the script:
2. Exit JShell After Executing A Script
If we run a script with JShell and we don’t exit the JShell, then the JShell session still remains to open. For example, let’s see another simple JShell script /opt/jshell-script-example.java with the following content:
1 |
System.out.println("Hello. This is a JShell script."); |
Let’s execute the script with JShell:
1 |
jshell /opt/jshell-script-example.java |
Let’s see the output of the script:
We can see that the JShell still remains opening. To exit JShell after executing a script, we can put a the /exit command at the end of the script. For example, let’s modify the above JShell script and put the /exit command at the end of the script.
1 2 3 4 5 |
System.out.println("Hello. This is a JShell script."); // Exit the JShell session /exit |
And then execute the JShell script again and observe the output:
We can see that the JShell session now is closed.
3. Conclusion
The tutorial has illustrated us how to execute a script with JShell and how to exit JShell after executing a script as well. We can see that both of them are pretty simple. To run a script with JShell, we simply need to put the path to the script at the first parameter of the JShell command while to exit JShell after executing, we just need to put the /exit command at the end of the script.
Below are other Java 9 related tutorials for your references:
How To Import The External Library Into Java 9 Shell
Java 9 – New Methods Of The Optional Class
How To Compare Arrays In Java 9
Java 9 HTTP/2 Client API Example
Java 9 – Effectively Final Variables In try-with-resources
Thanks for sharing. Nice post. just for completion it would be nice if you cower how to pass arguments to script and how to ask for input.