Stefano Locati

Programming Adventures (WIP)

Command line parsing example in Groovy

Here is an example using CliBuilder. I wrote it as an example for my stackoverflow question.

[sourcecode language="groovy"]


def cli = new CliBuilder(usage: 'cliTest -s sdkdir {projectName}',

header: 'Command line parameter parsing test in Groovy')

cli.s longOpt: 'sdkdir', args: 1, 'sdkdir usage info, REQUIRED'

cli.h longOpt: 'help', 'print usage information'

def opt = cli.parse(args)

def errMsg = "Invalid arguments.\nusage: ${cli.usage}\n" +

"Try `cliTest --help' for more information."

if (!opt) {

//should never happen, since I don't have required parameters in CliBuilder

println "error processing arguments\n"

} else if (opt.h) {


} else if (!opt.s) {

println errMsg

} else if (opt.arguments().size() != 1) {

println errMsg

} else {

println "Creating project ${opt.arguments()[0]}, sdkdir ${opt.s.value}"



The key is that opt.arguments() contains all arguments or options that I didn't test yet, as explained in GROOVY 3272 issue (thanks @rodion for spotting it).