Sub topic 13
Running, saving and loading scripts
This chapter assumes you can start a JShell session and that you know how snippets and slash commands work from earlier chapters. You need a JDK 9 or later with jshell on the PATH. By the end, you will be able to run a script file, save a session to a file, reload it later, and avoid the common problems with each.
Why scripts matter
A JShell session lives only in memory. When you type /exit, your variables, methods and classes are gone. A script is a plain text file that holds snippets and slash commands, so you can replay a session without retyping it.
By convention, script files use the .jsh extension. JShell does not require it. Any text file works, including a .java file that contains only snippets.
Running a script at launch
Pass the file name after the options:
jshell demo.jshJShell reads the file and evaluates each snippet in order, the same way it would if you had typed them. A script can contain slash commands as well as Java. Here is a complete script:
int x = 10;
System.out.println(x * 2);
/exitSaved as demo.jsh, it prints 20, and the final /exit ends the session.
If you leave out /exit, JShell finishes the file and then gives you an interactive prompt. The variables from the script are still defined, so you can keep working with them. This is useful for setting up a scratch environment.
You can pass several files. JShell loads them in the order you list them:
jshell setup.jsh helpers.jshLoading a script inside a session
Use /open to load a file into a session that is already running:
jshell> /open helpers.jsh
jshell> /methods
| int square(int)The snippets in the file are added to your current session. They do not replace it. If the file declares a name that already exists, the new declaration replaces the old one, as it would if you had typed it yourself.
Relative paths are resolved against the directory where you started jshell. If /open reports that it cannot find a file, check that directory first.
/open also accepts a few built-in names instead of a path: DEFAULT, PRINTING and JAVASE. These load predefined sets of imports and helper methods.
Saving a session
The /save command writes your snippets to a file:
jshell> int square(int x) { return x * x; }
| created method square(int)
jshell> square(5)
$2 ==> 25
jshell> /save session.jshThe file now holds the source text of the snippets:
int square(int x) { return x * x; }
square(5)The output $2 ==> 25 is not saved. A script holds only the input you typed, not what JShell printed back.
Choosing what to save
/save has options that change which snippets are written:
| Command | What it writes |
|---|---|
| `/save file` | Only the active snippets: the ones still in effect. Dropped, replaced and failed snippets are left out. |
| `/save -all file` | All snippets, including dropped, replaced and rejected ones. |
| `/save -history file` | Everything you typed, in order, including slash commands. |
| `/save -start file` | The current startup snippets, not your session. |
Plain /save gives the cleanest script. If you redefined square three times, only the final version is saved. -history is better when you want a record of exactly what you did, including commands such as /drop.
How saving and loading fit together
Rebuilding a session with /reload
/reload resets the session and replays the snippets you entered. It is a faster way to apply a change than quitting and relaunching. /reset clears the state without replaying anything.
A reasonable workflow is to keep a script open in a text editor. Edit it, then run /reset followed by /open myscript.jsh. You get a fresh state each time, so old definitions cannot hide a mistake in the new script.
Common problems
Scratch variables may not line up
Scratch variable names such as $2 come from the snippet's number. If your script uses $2 and the snippets are saved or loaded in a different order or count, $2 may refer to something else, or to nothing. Give results real names in any script you plan to keep:
int squared = square(5);
System.out.println(squared);Order matters for ordinary declarations
JShell allows forward references between methods, but a script is still evaluated top to bottom. A statement that calls a method before the method is declared fails at that point. Put declarations first and the statements that use them after.
A script is not a program
A .jsh file is not a Java source file. It has no class or main method, and javac cannot compile it. JShell also has relaxed rules, such as redeclaring a variable with a different type. If you want the code to become an application, you will need to wrap it in a class later.
Slash commands only work in JShell
A .jsh file containing /exit or /open is valid for JShell. Those lines are not Java, so the same file will not compile elsewhere.
Paths and the class path
If your script uses a library, load it with --class-path at launch, as described in the class path chapter. A script that imports a missing class will report an error for those snippets.
Putting it together
A typical workflow:
- Experiment interactively until the snippets work.
- Run
/save mytool.jshto keep the active snippets. - Open
mytool.jshin an editor and replace scratch variables with named ones. - Add
/exitat the end if the script should run and stop. - Run it with
jshell mytool.jsh.
Exercise
You run jshell setup.jsh and the script does not end with /exit. What state is the session in when the script finishes, and how would you make JShell quit automatically?
Show answer
The session stays open at an interactive prompt, and every variable, method and class from the script is still defined. To make JShell quit automatically, add /exit as the last line of the script.
Exercise
You redefined a method square twice and dropped a variable names during a session. Which /save form writes only the final square and leaves out names, and which form keeps every command you typed?
Show answer
Plain /save file writes only the active snippets, so it contains the final square and not the dropped names. /save -history file keeps everything you typed, including the redefinitions and the /drop command.
Exercise
A saved script contains the line $1 + 8. Why is this fragile, and what is the fix?
Show answer
$1 depends on the number of the snippet that produced it. If the script is loaded in a different order, or earlier snippets change, $1 may refer to a different value or to nothing. The fix is to assign the value to a named variable, such as int base = 6 * 7;, and use base + 8.