Command Line Flags in Groovy
Here’s the translation of the Go code example to Groovy, formatted in Markdown suitable for Hugo:
Command-line flags are a common way to specify options for command-line programs. For example, in wc -l
the -l
is a command-line flag.
Groovy provides the CliBuilder
class from the groovy.cli.picocli
package for parsing command-line options. We’ll use this class to implement our example command-line program.
In this example, we create a CliBuilder
instance and define our command-line options:
word
: A string option with a default value of “foo”numb
: An integer option with a default value of 42fork
: A boolean optionsvar
: Another string option with a default value of “bar”
After defining the options, we parse the command-line arguments using cli.parse(args)
. We then check if the help option was specified, and if so, we print the usage information and exit.
Finally, we print out the parsed options and any trailing positional arguments.
To experiment with the command-line flags program, save it as command-line-flags.groovy
and run it using the groovy
command:
Note that if you omit flags, they automatically take their default values:
Trailing positional arguments can be provided after any flags:
Use the -h
or --help
flag to get automatically generated help text for the command-line program:
If you provide a flag that wasn’t specified, the program will print an error message and show the help text.