Groovy中如何使用CliBuilder实现无选项仅位置参数的命令行脚本
Groovy CliBuilder 处理无选项位置参数实现
CliBuilder 本身原生支持位置参数解析,不需要硬编码拆分参数,核心逻辑是:所有未匹配到你预先声明的选项(比如-h/--help)的入参,都会被自动收集到解析结果对象的arguments属性里,按传入顺序存储,直接读取校验即可。
以下是符合需求的完整可运行脚本示例:
#!/usr/bin/env groovy import groovy.cli.commons.CliBuilder // 预定义所有支持的task profile def validTaskProfiles = ['task-1', 'task-2', 'task-3'] // 初始化CliBuilder时直接在usage里标明位置参数占位符,帮助信息更直观 def cli = new CliBuilder( usage: './someTask.groovy [options] <task-profile>', header: 'Available options:' ) // 注册帮助选项 cli.h(longOpt: 'help', 'Print help information and list all supported task profiles') // 解析入参 def parsedOptions = cli.parse(args) // 入参格式不符合CliBuilder规则时会自动打印错误,直接退出即可 if (!parsedOptions) { System.exit(1) } // 处理帮助查询请求 if (parsedOptions.h) { cli.usage() println "\nSupported task profile values:" validTaskProfiles.each { profile -> println " - $profile" } println "\nUsage example: ./someTask.groovy task-1" System.exit(0) } // 读取位置参数 def positionParams = parsedOptions.arguments // 校验位置参数数量 if (positionParams.size() != 1) { System.err.println "Error: You must specify exactly one task profile." cli.usage() System.exit(1) } def selectedProfile = positionParams[0] // 校验profile合法性 if (selectedProfile !in validTaskProfiles) { System.err.println "Error: Invalid task profile '${selectedProfile}'" System.err.println "Allowed values are: ${validTaskProfiles.join(', ')}" System.exit(1) } // 下方编写对应任务的实际执行逻辑即可 println "Running task with profile: ${selectedProfile}"
关键说明
- 位置参数不需要提前在CliBuilder中做任何声明,解析器会自动把不属于已注册选项的内容归集到
arguments列表,哪怕选项插在位置参数中间(比如./someTask.groovy task-1 -h)也能正确识别,不会把选项错当成位置参数。 - 可以根据需求扩展位置参数数量,比如需要2个位置参数就判断
positionParams.size() == 2,按顺序取对应索引的值即可。 - 帮助信息的输出可以根据需要调整格式,示例里的输出已经覆盖了所有可用profile说明和调用示例的要求。
调用效果示例
- 查看帮助:
./someTask.groovy --help
会输出完整用法、选项说明、支持的profile列表、调用示例。
- 正常执行任务:
./someTask.groovy task-3
脚本校验通过后会进入对应任务的执行逻辑。
- 传入非法值/参数数量不对时,会打印明确的错误提示,引导用户查看帮助。
内容的提问来源于stack exchange,提问作者BeastMaster64
相关产品推荐
相关产品推荐

