Sub topic 14
Customizing the JShell Startup Script
This chapter assumes that you have a JDK 9 or later, can start JShell from a terminal, and understand basic Java imports, variables, and methods.
A JShell startup script is a file containing snippets that JShell loads when a session begins. It is useful for imports, helper methods, constants, and feedback settings that you use repeatedly.
The startup sequence
JShell can load startup content from several places. Command-line options have the most direct control.
The default startup content provides commonly used imports. You can add your own file with --startup:
jshell --startup ~/.config/jshell/startup.jshA startup file can contain ordinary Java snippets and JShell commands. For example, startup.jsh could contain:
import java.time.LocalDate;
import java.util.List;
String todayLabel() {
return LocalDate.now().toString();
}
List<String> sampleNames = List.of("Ada", "Grace");When JShell starts with this file, todayLabel() and sampleNames are already available.
Retaining a startup script
The /set start command changes the startup script associated with JShell. Use -retain when you want JShell to remember the choice for later sessions.
jshell> /set start -retain /home/sam/.config/jshell/startup.jshThe path must point to a file that exists. On another operating system, use that system's path format.
Use /set start -default to restore JShell's default startup configuration:
jshell> /set start -defaultA retained startup script affects future sessions. It does not provide a reliable way to rerun all its snippets in the current session. To load a script into the current session, use /open:
jshell> /open /home/sam/.config/jshell/startup.jsh/open reads the file and evaluates its snippets in the current session. If the file declares a variable or method that already exists, JShell may replace that declaration.
| Goal | Command |
|---|---|
| Use a file for one session | `jshell --startup startup.jsh` |
| Set a retained startup file | `/set start -retain startup.jsh` |
| Restore the default startup setup | `/set start -default` |
| Load a file now | `/open startup.jsh` |
Choosing what to retain
Use a startup file for conveniences that belong to nearly every session. Keep project-specific classes and libraries in a separate script or use --class-path when needed. This avoids making unrelated experiments depend on hidden session state.
Exercise
You want LocalDate and a helper method named today() in every new JShell session, but you do not want to modify the current session. Which approach should you use?
Show answer
Put the import and method in a startup file, then run jshell --startup startup.jsh for one-time use or /set start -retain startup.jsh to make it the retained startup script.