deewreck
deewreck

Reputation: 133

groovy command line argument parsing

How can i safely parse command line arguments in groovy script. Assuming i need atleast 1 value in command line but there could be multiple values which can also be supplied. do i need to check size of args[] everytime before accessing any argument

def local = ""
def date=""
if (args.size() == 1) {
    local = (String) this.args[0]
    date = this.args[1] // this will give me indexoutofbound if no second argument supplied
}
else {
    println "Incorrect parameters !!"
    System.exit(0)
}

i need a way to easily move through if value of "date" is not provided, i can do null check on date and work on it later in code.

Upvotes: 0

Views: 746

Answers (1)

daggett
daggett

Reputation: 28564

you have to ensure size before getting item from array

however you could use a shorter syntax

def local1 = args.size()>0 ? args[0] : null
def local2 = args.size()>1 ? args[1] : null

v2. list.getAt(i) returns null on missing index

def argList = args.toList()

def local1 = argList[0]  // [x] => getAt(x)
def local2 = argList[1] 

Upvotes: 1

Related Questions