Command Line Arguments in Groovy

Our first program demonstrates how to use command-line arguments. Here’s the full source code:

import groovy.cli.CliBuilder

class CommandLineArguments {
    static void main(String[] args) {
        def cli = new CliBuilder(usage: 'groovy CommandLineArguments.groovy [options] <arg1> <arg2> ...')
        cli.parse(args)

        // args provides access to raw command-line arguments
        // Note that in Groovy, args already excludes the program name
        def argsWithoutProg = args

        // You can get individual args with normal indexing
        def arg = args.size() > 2 ? args[2] : null

        println("All arguments: ${args}")
        println("Arguments without program: ${argsWithoutProg}")
        println("Third argument (if exists): ${arg}")
    }
}

In Groovy, command-line arguments are automatically available in the args array passed to the main method. Unlike in some other languages, args in Groovy does not include the program name as the first element.

To experiment with command-line arguments, save the code in a file named CommandLineArguments.groovy and run it using the groovy command:

$ groovy CommandLineArguments.groovy a b c d
All arguments: [a, b, c, d]
Arguments without program: [a, b, c, d]
Third argument (if exists): c

In this example, we’re using Groovy’s CliBuilder class, which provides a more sophisticated way to handle command-line options and arguments. While it’s not necessary for this simple example, it’s a powerful tool for more complex command-line interfaces.

Note that Groovy scripts can be run directly without a separate compilation step, which is different from compiled languages like Java.

Next, we’ll look at more advanced command-line processing with options and flags using Groovy’s CliBuilder.