Skip to content

Instantly share code, notes, and snippets.

@onjin
Created January 14, 2026 07:42
Show Gist options
  • Select an option

  • Save onjin/21cb5334c05163c2a9d0d2f7d722cf89 to your computer and use it in GitHub Desktop.

Select an option

Save onjin/21cb5334c05163c2a9d0d2f7d722cf89 to your computer and use it in GitHub Desktop.
Example java as script
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
record Options(
boolean verbose,
List<String> inputs
) {}
public static void main(String[] args) {
Options opts = parseArgs(args);
if (opts.verbose()) {
System.out.println("Verbose mode on");
System.out.println("Inputs : " + opts.inputs());
}
// do your work here...
System.out.println("Scripted");
}
private static Options parseArgs(String[] args) {
boolean verbose = false;
List<String> inputs = new ArrayList<>();
for (int i = 0; i < args.length; i++) {
String a = args[i];
switch (a) {
case "-h", "--help" -> {
printUsage();
System.exit(0);
}
case "-v", "--verbose" -> verbose = true;
default -> {
if (a.startsWith("-")) {
System.err.println("Unknown option: " + a);
printUsage();
System.exit(1);
} else {
// positional argument
inputs.add(a);
}
}
}
}
return new Options(verbose, List.copyOf(inputs));
}
private static String requireValue(String[] args, int i, String opt) {
if (i >= args.length) {
System.err.println("Option " + opt + " requires a value");
printUsage();
System.exit(1);
}
return args[i];
}
private static void printUsage() {
String usage = """
Usage: example [OPTIONS] [INPUTS...]
Options:
-h, --help Show this help message and exit
-v, --verbose Enable verbose output
Examples:
./example input1.txt input2.txt
./example -v input1.txt
""";
System.out.print(usage);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment