Run shebang scripts
Starting with version 11, Java provides a way to run self-contained scripts without the need to compile them (https://openjdk.java.net/jeps/330). Furthermore, on Linux and macOS, you can make a Java script executable by specifying the JDK in the first line of the script.
This is called the shebang mechanism. Shebang support in Java comes in handy when you need to write an executable script, but cannot use a scripting language like bash or Python.
Write a script
Create a file without the
.java
extension.Start the first line with
#!
followed by the path to the JDK that will be used to run the script. Usesource
to specify the language level of the script. Language level 11+ is required.Example:
#!/usr/lib/jvm/openjdk-14.0.1/bin/java --source 11
Write the body of the script. The script can contain multiple classes and use imports from the standard library. The entry point has to be defined as
public static void main(String[] args)
in the first declared class.Below is an example of a valid shebang script:
#!/usr/lib/jvm/openjdk-14.0.1/bin/java --source 11 import java.util.Locale; class Hello { public static void main(String[] args) { String lang = Locale.getDefault().getLanguage(); System.out.println(Greetings.getGreeting(lang)); } } class Greetings { static String getGreeting(String lang) { switch (lang) { case "fr": return "Bonjour"; case "es": return "Hola"; case "zh": return "Nǐn hǎo"; case "de": return "Guten Tag"; case "pl": return "Dzień dobry"; case "el": return "Yassas"; case "sv": return "God dag"; default: return "Hi"; } } }Make sure that the script file is executable using the
chmod +x
command.
Run a script
Click the Run icon in the gutter or press Control+Shift+F10.
Create a run/debug configuration. This can be useful if you want to pass parameters to your script, debug it, or run it as part of a compound workflow.
Debug a script
Create a run/debug configuration for the script and add a VM option to load the debug agent.
Attach to the process using the Remote JVM debug run/debug configuration.